看看C++连接数据库,取结果集的方法:
1.首先,头文件加下面一行:
#import "c:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF") rename("BOF", "adoBOF")
2.我把数据库连接写成一个函数:
_ConnectionPtr CDBase::ConectDB(void)
{
_ConnectionPtr pConnect = NULL;
CoInitialize(NULL);
if(FAILED(pConnect.CreateInstance(__uuidof(Connection))))
return NULL;
CString strConnects = "Provider=SQLOLEDB; Server="+dbConn.ip+"; Database="+dbConn.database+"; uid="+dbConn.uid+"; pwd="+dbConn.pwd+";";
_bstr_t strConnect= (_bstr_t)strConnects;
try
{
pConnect->Open(strConnect, "", "", NULL);
}
catch(_com_error& e){
MessageBoxA(0,"数据库连接失败!",0,0);
return NULL;
}
return pConnect;
}
3.sql查询结果:
void CDBase::GetDevList(void)
{
_RecordsetPtr pRecordset = NULL;
if(FAILED(pRecordset.CreateInstance(__uuidof(Recordset))))
return ;
_ConnectionPtr pConnect = ConectDB();
if (!pConnect)
return;
try
{
char* strSql = "select DevID,UDevID,Key from DEVLIST";//具体执行的SQL语句
pRecordset = pConnect->Execute(_bstr_t(strSql), NULL, adCmdText);//将查询数据导入pRecordset数据容器
_variant_t ID,UD,Key;
while(!pRecordset->adoEOF)
{
ID = pRecordset->GetCollect("DevID");//ID
UD = pRecordset->GetCollect("UDevID");
Key = pRecordset->GetCollect("Key");
}
}
catch (CException* e)
{
MessageBoxA(0,"数据库操作错误!",0,0);
}
pConnect->Close();
}