_ConnectionPtr
m_pConnection;
HRESULT hr;
try{
hr = m_pConnection.CreateInstance(_uuidof(Connection));///创建Connection实例
if(SUCCEEDED(hr)){
m_pConnection->ConnectionTimeout=600;//设置连接超时时间
m_pConnection->CommandTimeout=120;//设置执行命令超时时间
hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=My.mdb","","",adModeUnknown);///连接数据库
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
return FALSE;
}
// 关闭ADO连接状态
if (m_pConnection->GetState() == adStateOpen)
{
m_pConnection->Close();
}
if (m_pConnection)
{
m_pConnection.Release();
m_pConnection = NULL;
}
_RecordsetPtr:
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance("ADODB.Recordset");
m_pRecordset->Open(bstrSQL,_variant_t((IDispatch*)pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
if (m_pRecordset->GetState() == adStateOpen)
{
m_pRecordset->Close();
}
if (m_pRecordset)
{
m_pRecordset.Release();
m_pRecordset = NULL;
}
_CommandPtr:
_CommandPtr pCommandPtr;
try
{
hr = pCommandPtr.CreateInstance(_uuidof(Command));
if (SUCCEEDED(hr))
{
pCommandPtr->put_ActiveConnection(_variant_t((IDispatch*)pConnection,true));
pCommandPtr->CommandText=_bstr_t(strinSQL);
pCommandPtr->Execute(NULL,NULL,adCmdText);
}
}catch(_com_error *e)
{
return;
}
if (pCommandPtr)
{
pCommandPtr.Release();
pCommandPtr = NULL;
}