在 VC++ (MFC/ATL) 專案中,需要透過 ADO 或 ODBC 連接 Microsoft Access 資料庫,查詢指定欄位的最大值與最小值,並將結果顯示於對話方塊的編輯框中。適合初學 C++ 資料庫程式設計的開發者參考。
_ConnectionPtr、_RecordsetPtr 等 ADO 智慧指標。MAX()、MIN()。_variant_t) 與 C++ 型別轉換。#include
#import "msado15.dll" no_namespace rename("EOF", "adoEOF")
#include
void CMyDialog::QueryMinMax(CString strTable, CString strField, CEdit& editMin, CEdit& editMax)
{
try {
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRs(__uuidof(Recordset));
// 連接字串:Access 2007+ 使用 ACE.OLEDB.12.0
CString strConn = _T("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Data\\MyDB.accdb;Persist Security Info=False;");
pConn->Open(_bstr_t(strConn), _T(""), _T(""), adConnectUnspecified);
// SQL 查詢
CString strSQL;
strSQL.Format(_T("SELECT MIN([%s]) AS MinVal, MAX([%s]) AS MaxVal FROM [%s]"), strField, strField, strTable);
pRs->Open(_bstr_t(strSQL), pConn.GetInterfacePtr(), adOpenStatic, adLockReadOnly, adCmdText);
if (!pRs->adoEOF) {
_variant_t varMin = pRs->GetCollect(_T("MinVal"));
_variant_t varMax = pRs->GetCollect(_T("MaxVal"));
CString strMin, strMax;
if (varMin.vt != VT_NULL) strMin.Format(_T("%s"), (_bstr_t)varMin);
if (varMax.vt != VT_NULL) strMax.Format(_T("%s"), (_bstr_t)varMax);
editMin.SetWindowText(strMin);
editMax.SetWindowText(strMax);
}
pRs->Close();
pConn->Close();
}
catch (_com_error& e) {
AfxMessageBox(_T("資料庫錯誤: ") + CString(e.ErrorMessage()));
}
}
void CMyDialog::OnBnClickedBtnQuery()
{
QueryMinMax(_T("Products"), _T("Price"), m_editMin, m_editMax);
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 連接失敗 | 未安裝 Access Database Engine | 下載安裝 Microsoft Access Database Engine 2016 Redistributable (x64/x86 需與專案位元數一致) |
| 欄位名稱有空格 | SQL 語法錯誤 | 欄位名用方括號括起來,如 [Unit Price] |
| 結果為空 | 資料表無資料或欄位全 NULL | 程式碼已判斷 VT_NULL,顯示空字串 |
CDBAccess 類別,支援連線池與交易。CListCtrl 顯示多欄位統計結果。