開發一個地鐵查詢系統,已使用 MFC 搭配 ADO 成功連接 Access 資料庫。資料表儲存的是相鄰兩站之間的里程數據。現在需要實現:使用者輸入起點與終點,系統自動定位資料庫中的里程記錄並計算總里程輸出。
_ConnectionPtr 建立連線字串,開啟 Access 資料庫。_RecordsetPtr 執行 SQL 將所有邊(站點對、距離)讀入 std::vector 或鄰接表。_RecordsetPtr pRs;
pRs.CreateInstance(__uuidof(Recordset));
pRs->Open("SELECT StartStation, EndStation, Distance FROM StationDistance", pConn.GetInterfacePtr(), adOpenStatic, adLockReadOnly, adCmdText);
while (!pRs->adoEOF) {
CString start = pRs->GetCollect("StartStation");
CString end = pRs->GetCollect("EndStation");
double dist = pRs->GetCollect("Distance");
// 建立圖結構
graph[start].push_back({end, dist});
graph[end].push_back({start, dist}); // 雙向
pRs->MoveNext();
}
CComboBox 綁定站點清單,提升使用者體驗。_com_error 捕捉 ADO 例外。更完整的 MFC+ADO 範例可參考:百度經驗連結