ADO (ActiveX Data Objects) 是微軟推薦的高階資料存取介面,封裝 OLE DB 底層細節,比 ODBC/DAO/RDO 更易用且不失彈性。本文帶你從零建立第一個 ADO 應用。
Connection 物件連接資料庫Command 或 Recordset 執行 SQL、查詢處理資料// MFC 專案在 CWinApp::InitInstance 中
BOOL CMyApp::InitInstance() {
AfxOleInit(); // 或非 MFC 環境用 CoInitialize(NULL)
// ...
}
在 stdafx.h 加入:
#import "C:\\Program Files\\Common Files\\System\\ado\\msado15.dll" \
no_namespace rename("EOF", "adoEOF")
rename("EOF", "adoEOF") 避免與 MFC EOF 巨集衝突
_ConnectionPtr m_pConnection;
_CommandPtr m_pCommand;
HRESULT hr;
try {
hr = m_pConnection.CreateInstance(__uuidof(Connection));
if (SUCCEEDED(hr)) {
m_pConnection->ConnectionTimeout = 0;
hr = m_pConnection->Open(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb",
"", "", adModeUnknown);
m_pCommand.CreateInstance(__uuidof(Command));
m_pCommand->CommandTimeout = 5;
m_pCommand->ActiveConnection = m_pConnection;
}
}
catch (_com_error& e) {
CString msg; msg.Format(_T("連線失敗: %s"), e.ErrorMessage());
AfxMessageBox(msg);
}
if (m_pConnection->State) m_pConnection->Close();
m_pConnection = NULL;
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));
try {
m_pRecordset->Open(
"SELECT * FROM DemoTable",
m_pConnection.GetInterfacePtr(),
adOpenDynamic, adLockOptimistic, adCmdText);
}
catch (_com_error* e) {
AfxMessageBox(e->ErrorMessage());
}
while (!m_pRecordset->adoEOF) {
_variant_t var = m_pRecordset->GetCollect("Name");
if (var.vt != VT_NULL) CString strName = (LPCTSTR)_bstr_t(var);
var = m_pRecordset->GetCollect("Age");
if (var.vt != VT_NULL) CString strAge = (LPCTSTR)_bstr_t(var);
m_List.AddString(strName + _T(" --> ") + strAge);
m_pRecordset->MoveNext();
}
AddNew() → PutCollect() 賦值 → Update()PutCollect() → Update()Delete(adAffectCurrent) → Update()
m_pCommand->CommandText = "DELETE FROM DemoTable WHERE Age > 30";
m_pCommand->Execute(NULL, NULL, adCmdText);
掌握上述核心物件與流程,即可輕鬆開發 ADO 資料庫應用。下篇將深入 BLOB 處理與進階技巧。