2 回答

TA貢獻1951條經(jīng)驗 獲得超3個贊
_ConnectionPtr m_pConnection;
CoInitialize(NULL);
m_pConnection.CreateInstance(__uuidof(Connection));
// 在ADO操作中建議語句中要常用try...catch()來捕獲錯誤信息,
// 因為它有時會經(jīng)常出現(xiàn)一些想不到的錯誤。
try
{
// 打開本地Access庫db1.mdb
m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb","","",adModeUnknown);
}
catch(_com_error e)
{
cout<<"數(shù)據(jù)庫連接失敗,確認數(shù)據(jù)庫db1.mdb是否在當(dāng)前路徑下!"<<endl;
return FALSE;
}
//-------------------------------------------------------------------------------------
//建立數(shù)據(jù)集
//-------------------------------------------------------------------------------------
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));
// 在ADO操作中建議語句中要常用try...catch()來捕獲錯誤信息,
// 因為它有時會經(jīng)常出現(xiàn)一些意想不到的錯誤。
try
{
m_pRecordset->Open("SELECT * FROM Home2",
m_pConnection.GetInterfacePtr(), // 獲取庫接庫的IDispatch指針
adOpenDynamic,
adLockOptimistic,
adCmdText);
}
catch(_com_error *e)
{
//AfxMessageBox(e->ErrorMessage());
cout<<e->ErrorMessage()<<endl;
}
//--------------------------------------------------------------------------------------
//讀取數(shù)據(jù)
//--------------------------------------------------------------------------------------
_variant_t var;
char *strID,*strX,*strY;
float X,Y;
try
{
if(!m_pRecordset->BOF)
m_pRecordset->MoveFirst();
else
{
cout<<"表內(nèi)數(shù)據(jù)為空"<<endl;
return 1;
}
// 讀入庫中各字段并加入列表框中
while(!m_pRecordset->adoEOF)
{
var = m_pRecordset->GetCollect("ID");
if(var.vt != VT_NULL)
strID= _com_util::ConvertBSTRToString((_bstr_t)var); //_variant_t轉(zhuǎn)字符串
var = m_pRecordset->GetCollect("X");
if(var.vt != VT_NULL)
strX=_com_util::ConvertBSTRToString((_bstr_t)var);
var = m_pRecordset->GetCollect("Y");
if(var.vt != VT_NULL)
strY=_com_util::ConvertBSTRToString((_bstr_t)var);
cout<<strID<<"is"<<strX<<" "<<strY<<endl;
m_pRecordset->MoveNext();
}
}
catch(_com_error *e)
{
cout<<e->ErrorMessage()<<endl;
}
//--------------------------------------------------------------------------------------
//關(guān)閉數(shù)據(jù)集
m_pRecordset->Close();
m_pRecordset = NULL;
//--------------------------------------------------------------------------------------
//關(guān)閉數(shù)據(jù)庫連接
//--------------------------------------------------------------------------------------
if(m_pConnection->State)
m_pConnection->Close();
m_pConnection= NULL;
- 2 回答
- 0 關(guān)注
- 765 瀏覽
添加回答
舉報