_ConnectionPtr、_RecordsetPtr和_CommandPtr 打开和关闭

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
_ConnectionPtr:
_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)
{
if (m_pConnection->GetState() == adStateOpen)
{
m_pConnection->Close();
}

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)
{
if (m_pRecordset->GetState() == adStateOpen)
{
m_pRecordset->Close();
}

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;
}