C++ ADO

Connection 对象

Recordset 对象

Command 对象

引用类库

#import "D:\Program files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")

初始化COM

CoInitialize(NULL);
AfxOleInit();

定义对象

_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
_ConnectionPtr m_pConnection;
HRESULT hr;
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
if(SUCCEEDED(hr))
{
    // 创建成功
}

关闭对象

pRst->Close();
pConn->Close();
pRst.Release();
pConn.Release();

关闭 COM

CoUninitialize();

_com_error

发生异常时会抛出这个错误, 注意捕捉.

try { ... } catch( _com_error e) { ... }

示例

/**** In header file STDAFX.H ****/

#import "D:\Program files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")

void CAdoDlg::OnBtnQuery() 
{
	CoInitialize(NULL);
	_ConnectionPtr pConn(__uuidof(Connection));
	_RecordsetPtr pRst(__uuidof(Recordset));
	try
	{
		pConn->ConnectionString="Provider=SQLOLEDB.1;Initial Catalog=pubs;Trusted_Connection=yes";
		pConn->Open("","","",adConnectUnspecified);
		pRst = pConn->Execute("select * from authors",NULL,adCmdText);
		while(!pRst->rsEOF)
		{
			((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("au_lname"));
			pRst->MoveNext();
		}
		pRst->Close();
		pConn->Close();
	}
	catch(_com_error e)
	{
		char buff[100];
		strcpy(buff,(const char *)(e.ErrorMessage()));
		MessageBox(buff);
	}
	pRst.Release();
	pConn.Release();
	CoUninitialize();
}
关键词 意义
CoInitialize 初始化 COM 接口
_ConnectionPtr 智能指针
_bstr_t 数据转换成字符串