1.引入ADO
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
數據庫
2.建立鏈接數據庫類(兩個指針及四個成員函數)
class CADOConn
{
public:
CADOConn();
virtual ~CADOConn();ide
_ConnectionPtr m_pConnection; //對象智能指針鏈接操做數據庫
_RecordsetPtr m_pRecordPtr; //Recordset對象指針(記錄集)函數
//初始化鏈接數據庫,執行查詢,執行SQL語句,斷開鏈接
void OnInitDBConnect();
_RecordsetPtr &GetRecordSet(_bstr_t bstrSQL);
BOOL ExecuteSQL(_bstr_t bstrSQL);
void ExitConnect();ui
};spa
3.四個成員函數實現
void CADOConn::OnInitDBConnect()
{
::CoInitialize(NULL); //初始化OLE/COM庫環境
try
{
//建立connection對象
m_pConnection.CreateInstance("ADODB.Connection");
//設置鏈接字符串
_bstr_t strConnect="Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=本身數據庫填寫處;Data Source=.";
//SERVER和UID,PWD的設置根據實際狀況來設置
m_pConnection->Open(strConnect,"","",adModeUnknown);
}
catch(_com_error e)
{
AfxMessageBox(e.Description()); //顯示錯誤信息
}
}指針
_RecordsetPtr & CADOConn::GetRecordSet(_bstr_t bstrSQL)
{
try
{
if(m_pConnection==NULL) //鏈接對象不存在
OnInitDBConnect(); //從新鏈接
m_pRecordPtr.CreateInstance(_uuidof(Recordset)); //建立記錄集對象
//執行查詢,等到記錄集
m_pRecordPtr->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch(_com_error e) //捕捉異常
{
AfxMessageBox(e.Description()); //顯示錯誤信息
}
return m_pRecordPtr; //返回記錄集
}對象
BOOL CADOConn::ExecuteSQL(_bstr_t bstrSQL)
{
try
{
if(m_pConnection==NULL)
OnInitDBConnect();
m_pConnection->Execute(bstrSQL,NULL,adCmdText);
return true;
}
catch (_com_error e)
{
AfxMessageBox(e.Description());
return false;
}
}ip
void CADOConn::ExitConnect()
{
if(m_pConnection!=NULL)
{
m_pRecordPtr->Close();
m_pConnection->Close();
}
::CoUninitialize();
}字符串