//ado连接sql server
//头文件加上以下这句。
#import "C:\Windows\system\msado15.dll" no_namespace rename("EOF","rsEOF")
</pre><pre code_snippet_id="620722" snippet_file_name="blog_20150316_3_7210460" name="code" class="cpp">//cpp里面
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
_CommandPtr pCmd(__uuidof(Command));
try{//以下是从windows身份验证进入的。sql server身份验证在我的机子上还为调试出来
pConn->ConnectionString="Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=WIN7-20120101NA\\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=WIN7-20120101NA;Use Encryption for Data=False;Tag with column collation when possible=False";
//pConn->ConnectionString="Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=test;Data Source=WIN7-20120101NA\\SQLEXPRESS;";
//凝视里的表示必须包括的字段
pConn->Open("","","",adConnectUnspecified); //打开连接
pRst=pConn->Execute("select * from [dbo].[user]",NULL,adCmdText); //读取user表
_variant_t vUsername;
while(!pRst->rsEOF)
{
vUsername=pRst->GetCollect("id");
CString message;
message.Format("%s",(LPCTSTR)(_bstr_t)vUsername);
AfxMessageBox(message);///显示当前记录条数
pRst->MoveNext();
}
}catch (_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s", e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
return;
}
pRst->Close();
pConn->Close();
pCmd.Release();
pRst.Release();
pConn.Release();
CoUninitialize();