ADO (ActiveXData Objects,ActiveX數據對象)是Microsoft提出的應用程序接口(API)用以實現訪問關係或非關係數據庫中的數據。 ADO 使您能夠編寫應用程序以通過 OLE. DB提供者訪問和操作數據庫服務器中的數據。相對於直接訪問ODBC接口,ADO更便捷。
下面介紹下在VC環境,通過ADO鏈接和操作SQLServer數據庫的一般方法:
在VC中使用ADO數據庫,主要是使用ADO所提供的Connection、Command、和Recordset對象來進行對數據庫的訪問。
一:導入ADO庫文件
使用ADO訪問數據庫要用到msado15.dll庫文件。這個文件的一般路徑是:C:\ProgramFiles\CommonFiles\System\ado\msado15.dll
導入方法,加入如下代碼段:
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")
語句no_namespace的作用是,設置調用的dll中的函數沒有名稱空間。renam("EOF","rsEOF")只是爲了避免EOF和C++中EOF混淆。
二、初始化OLE/COM庫環境
ADO
ADO庫是一組COM動態庫,程序在調用ADO前,須初始化OLE/COM庫環境。可以調用WindowsAPI::Initialize(NULL),當然在使用後要記着調用::Uninitialize()釋放。三、使用ADO對象,操作數據庫
1.使用Connection
代碼如下:
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRs(__uuidof(Recordset));
pConn->ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=bbs";
pConn->Open("","sa","sql2008",adConnectUnspecified);
pRs = pConn->Execute("select * from article",NULL,adCmdText);
while(!pRs->rsEOF)
{
printf((_bstr_t)pRs->GetCollect("title"));
printf("\n");
pRs->MoveNext();
}
pRs.Release();
pConn.Release();
::CoUninitialize();
return 0;
}
2.使用Command
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
_CommandPtr pCmd(__uuidof(Command));
pConn->ConnectionString="Provider=
SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=bbs";
pConn->Open("","sa","sql2008",adConnectUnspecified);
pCmd->put_ActiveConnection(_variant_t((IDispatch*)pConn));
pCmd->CommandText="select * from article";
pRst=pCmd->Execute(NULL,NULL,adCmdText);
while(!pRst->rsEOF)
{
printf((_bstr_t)pRst->GetCollect("title"));
printf("\n");
pRst->MoveNext();
}
pRst->Close();
pConn->Close();
pCmd.Release();
pRst.Release();
pConn.Release();
::CoUninitialize();
return 0;
}