C++連線資料庫的方法
阿新 • • 發佈:2018-11-28
看看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(); }