完整程式碼範例
// 假設 m_pConnection 已建立且開啟
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));
#ifdef _DEBUG
if (m_pRecordset == NULL) {
AfxMessageBox(_T("Recordset 建立失敗,請確認 COM 已初始化"));
return;
}
#endif
try {
_variant_t sql(_T("TestGet")); // 存儲過程名稱
m_pRecordset->Open(sql,
_variant_t((IDispatch*)m_pConnection, true),
adOpenStatic, adLockOptimistic, adCmdStoredProc);
long count = m_pRecordset->GetRecordCount();
if (!m_pRecordset->adoEOF) {
for (long i = 0; i < count; ++i) {
_variant_t val = m_pRecordset->GetCollect(_T("Account"));
CString str = (LPCTSTR)(_bstr_t)val;
AfxMessageBox(str);
m_pRecordset->MoveNext();
}
}
m_pRecordset->Close();
}
catch (_com_error& e) {
CString msg;
msg.Format(_T("錯誤: %s\n檔案: %s\n行: %d"), e.ErrorMessage(), __FILE__, __LINE__);
AfxMessageBox(msg);
}
關鍵點說明
adCmdStoredProc 告知 ADO 執行的是存儲過程而非 SQL 字串。
_variant_t((IDispatch*)m_pConnection, true) 正確傳遞連線物件並 AddRef。
- 若改為動態 SQL,將
sql 設為 SQL 字串,移除 adCmdStoredProc 旗標。
- 記得在
InitInstance 呼叫 CoInitialize(NULL),ExitInstance 呼叫 CoUninitialize()。