>基础环境设置
初始化com库 使用AfxOleInit()函数,可以在MFC环境中使用.
>定义一个connection对象,并登录sqlserver服务器
Connection15Ptr pConnection;
pConnection.CreateInstance("ADODB.Connection");
_bstr_t bstr_Connectionstring;
bstr_Connectionstring = SysAllocString(L"Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;User ID=sa;Initial Catalog=Northwind;Data Source=.");
pConnection->Open(bstr_Connectionstring,_bstr_t(""),_bstr_t(""),adConnectUnspecified );
pConnection->Close();
>定义一个RecordSet对象,并查询数据集
Recordset15Ptr pRecordset;
pRecordset.CreateInstance("ADODB.Recordset");
VARIANT vtRecord;
vtRecord.vt = VT_I4;
BSTR bstr_CommandText = SysAllocString(L"SELECT * FROM dbo.Employees");
pRecordset = pConnection->Execute(bstr_CommandText,&vtRecord,adCmdText );
while(!pRecordset->AdoEOF)
{
OutputDebugString( (char*) ((_bstr_t) pRecordset->Fields->Item["FirstName"]->Value));
OutputDebugString("\n");
pRecordset->MoveNext();
}
pRecordset->Close();