VS利用ADO連接數(shù)據(jù)庫的操作
(1)初始化COM庫,引入ADO庫定義文件
(2)用Connection對(duì)象連接數(shù)據(jù)庫
(3)利用建立好的連接,通過Connection、Command對(duì)象執(zhí)行SQL命令,或利用Recordset對(duì)象取得結(jié)果記錄集進(jìn)行查詢、處理。
(4)使用完畢后關(guān)閉連接釋放對(duì)象。
#include#include#include#import?"C:msado15.dll"?no_namespace?rename("EOF","adoEOF")?rename("BOF","adoBOF")
using?namespace?std;
int?main(void)
{
CoInitialize(NULL);
_ConnectionPtr?pCon(__uuidof(Connection));
_RecordsetPtr?pRSet(__uuidof(Connection));
try
{
pCon.CreateInstance("__uuidof(Connection)");
}?
catch(_com_error?e)
{
cout<<"創(chuàng)建連接實(shí)例失敗!"<<endl;
cout<<e.Description()<<endl;
cout<<e.HelpFile()<Open("driver={SQL?Server};Server=.;DATABASE=linping;","sa","",adModeUnknown);
}?
catch(_com_error?e)
{
cout<<"數(shù)據(jù)庫初始化失敗!"<<endl;
cout<<e.Description()<<endl;
cout<<e.HelpFile()<<endl;
return?0;
}
cout<<"連接成功!"<Execute("select?*?from?card",NULL,adCmdText);
if(!pRSet->adoBOF)
{
pRSet->MoveFirst();
}
else
{
cout<<"表內(nèi)數(shù)據(jù)為空!"<<endl;
return?0;
}
vectorcolumn_name;
for(int?i?=?0;iFields->GetCount();i++)
{
cout<Fields->GetItem(_variant_t((long)i))->Name<Fields->GetItem(_variant_t((long)i))->Name);
}
while(!pRSet->adoEOF)
{
vector::iterator?iter?=?column_name.begin();
for(iter;iter!=column_name.end();iter++)
{
if(pRSet->GetCollect(*iter).vt?!=VT_NULL)
{
cout<GetCollect(*iter)<<endl;
}
else
{
cout<<"NULL"<MoveNext();
cout<<endl;
}
}?
catch(_com_error?&e)
{
cout<<e.Description()<<endl;
cout<<e.HelpFile()<Close();
pCon->Close();
pRSet.Release();
pCon.Release();
}
catch(_com_error?&e)
{
cout<<e.Description()<<endl;
cout<<e.HelpFile()<<endl;
return?0;
}
CoUninitialize();
return?0;
}?





