VC使用ADO访问sql server数据库

软件:vs2010、sql server2005
代码如下:
#include 
#include 
using namespace std;
//1、添加对ADO的支持
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")


int main()
{
CoInitialize(NULL);


//2、创建实例
_ConnectionPtr   pCon(__uuidof(Connection));
_RecordsetPtr    pReS(__uuidof(Recordset));
_CommandPtr      pCmd(__uuidof(Command));


//3、打开数据库连接
try{
//pCon->Open("Provider=SQLOLEDB;Data Source=Localhost,1433;Initial Catalog=QPTreasureDB;uid=sa;pwd=123;","","",adConnectUnspecified);
pCon->Open("Provider=SQLOLEDB;Data Source=Localhost,1433;uid=sa;pwd=123;","","",adConnectUnspecified);
}
catch(...){
cout<<"打开数据库失败。。。"<Execute(_bstr_t(strSql),NULL,adCmdText);


//---------方式 2)、_RecordsetPtr----------------
//pReS->Open(_variant_t(strSql),(_variant_t)( (IDispatch*)pCon),adOpenDynamic,adLockOptimistic,adCmdText);


//---------方式 3)、_CommandPtr----------------
//pCmd->put_ActiveConnection((_variant_t)((IDispatch*)pCon));
//pCmd->CommandText=_bstr_t(strSql);
//pReS=pCmd->Execute(NULL,NULL,adCmdText);


//操作数据
while(!pReS->adoEOF)
{
//_variant_t  var=pReS->GetCollect("Score");
//var.ChangeType(VT_DECIMAL); //或者"(DECIMAL)var;"(重载了DECIMAL)
//ULONGLONG score=var.decVal.Lo64;


//重载了ULONGLONG,另外如果查到的Score不是数字而是字符串,则需先_bstr_t转换:_bstr_t(pReS->GetCollect("Score"))
ULONGLONG score=pReS->GetCollect("Score");  
cout<<"the Score is "<MoveNext();
}
}
catch(_com_error& e)
{
cout<<"操作数据库时出错:"<Close();
pCon->Close();
pReS.Release();   //注意是'.'不是'->'
pCon.Release();
pCmd.Release();
}
catch(_com_error& e)
{
cout<<"释放资源时出错:"<


你可能感兴趣的:(sql,server,C++)