在 VC++ 中利用 ADO (ActiveX Data Objects) 連接 Access 2000 (.mdb) 數據庫,獲取其中所有用戶表(非系統表、視圖)的名稱,填充至列表控件供用戶選擇。
void OpenSchemaX(TCHAR *TableName) {
HRESULT hr = S_OK;
::CoInitialize(NULL); // 初始化 COM 庫
IADORecordBinding *picRs = NULL;
_RecordsetPtr pRstSchema("ADODB.Recordset");
_ConnectionPtr pConnection("ADODB.Connection");
// 構建連接字符串
pConnection->ConnectionString = TableName; // 實為 .mdb 文件路徑
pConnection->Provider = "Microsoft.Jet.OLEDB.4.0";
try {
pConnection->Open(pConnection->ConnectionString, "", "", adModeUnknown);
pRstSchema->QueryInterface(__uuidof(IADORecordBinding), (LPVOID*)&picRs);
// 關鍵:OpenSchema 獲取表架構
pRstSchema = pConnection->OpenSchema(adSchemaTables);
while(!(pRstSchema->EndOfFile)) {
CString strTableType;
_bstr_t table_name = pRstSchema->Fields->GetItem("TABLE_NAME")->Value;
_bstr_t table_type = pRstSchema->Fields->GetItem("TABLE_TYPE")->Value;
strTableType.Format("%s", (LPCSTR)table_type);
// 過濾:僅保留用戶表 (TABLE)
if(!lstrcmp(strTableType, _T("TABLE"))) {
m_strList.AddString((LPCSTR)table_name); // 添加到列表框
}
pRstSchema->MoveNext();
}
pRstSchema->Close();
pConnection->Close();
}
catch (_com_error &e) {
PrintProviderError(pConnection);
PrintComError(e);
}
CoUninitialize();
}
void PrintProviderError(_ConnectionPtr pConnection) {
ErrorPtr pErr = NULL;
if((pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
for(long i = 0; i < nCount; i++) {
pErr = pConnection->Errors->GetItem(i);
CString strError;
strError.Format("Error number: %x\t%s", pErr->Number, pErr->Description);
AfxMessageBox(strError);
}
}
}
void PrintComError(_com_error &e) {
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
CString strError;
strError.Format("Error number: Description = %s\tCode meaning = %s",
(LPCSTR)bstrDescription, e.ErrorMessage());
AfxMessageBox(strError);
}
CString strFileName;
TCHAR FileName[MAX_PATH];
TCHAR bigBuff[2048] = _T("");
TCHAR szFilter[] = _T("Access Files (*.mdb)|*.mdb|All Files (*.*)|*.*||");
CFileDialog dlg(TRUE, NULL, NULL,
OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT, szFilter);
dlg.m_ofn.lpstrFile = bigBuff;
dlg.m_ofn.nMaxFile = sizeof(bigBuff);
if(IDOK == dlg.DoModal()) {
strFileName = dlg.GetPathName();
lstrcpy(FileName, strFileName);
OpenSchemaX(FileName);
}
msado15.dll (ADO 2.x) 並導入命名空間或使用智能指針 (_ConnectionPtr 等)。OpenSchema(adSchemaTables) 返回包含 TABLE_NAME, TABLE_TYPE, TABLE_CATALOG 等字段的記錄集。TABLE_TYPE 為 "TABLE" 表示用戶表;"SYSTEM TABLE" 為系統表;"VIEW" 為視圖。_bstr_t 自動管理 BSTR 生命周期;智能指針自動 Release。