最近在使用 MFC 連接 MySQL 數據庫時出現了連接失敗的情況,經過多次嘗試,總結了以下幾點可能的原因。
// 嘗試連接數據庫 CDatabase database; CString sDsn; sDsn.Format(_T("ODBC;DRIVER={MySQL ODBC 5.3 ANSI Driver};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s;PORT=%d"), SERVERNAME, USERNAME, PASSWORD, DATABASE, PORT); TRY { database.Open(NULL, FALSE, FALSE, sDsn); } CATCH (CDBException, e) { // 輸出連接失敗的錯誤信息 AfxMessageBox(e->m_strError); } END_CATCH
1. MySQL ODBC 驅動未安裝或版本不匹配
// 在注冊表中查找 MySQL ODBC 驅動是否安裝 HKEY hKey = NULL; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\ODBC\\ODBCINST.INI\\MySQL ODBC 5.3 ANSI Driver"), 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS) { // 驅動未安裝 AfxMessageBox(_T("MySQL ODBC 5.3 ANSI Driver not found, please install it first!")); } else { // 驗證驅動版本是否匹配 TCHAR szPath[MAX_PATH] = { 0 }; DWORD dwSize = sizeof(szPath); if (RegQueryValueEx(hKey, _T("Driver"), NULL, NULL, (LPBYTE)szPath, &dwSize) != ERROR_SUCCESS) { // 無法獲取驅動路徑 AfxMessageBox(_T("Can't find MySQL ODBC driver path, please reinstall it!")); } else { // 判斷驅動版本是否匹配 CString sDriverVersion = _T(""); GetModuleVersion(szPath, sDriverVersion); if (sDriverVersion != _T("5.3.13.0")) { AfxMessageBox(_T("MySQL ODBC driver version does not match, please install version 5.3.13.0!")); } } RegCloseKey(hKey); }
2. MySQL 服務未啟動或端口異常
// 查詢 MySQL 服務狀態是否正常 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if (hSCM == NULL) { AfxMessageBox(_T("Failed to open Service Control Manager!")); } else { SC_HANDLE hService = OpenService(hSCM, _T("MySQL"), SERVICE_QUERY_STATUS); if (hService == NULL) { AfxMessageBox(_T("Failed to open MySQL service!")); } else { SERVICE_STATUS ss = { 0 }; if (QueryServiceStatus(hService, &ss)) { if (ss.dwCurrentState != SERVICE_RUNNING) { AfxMessageBox(_T("MySQL service is not running, please start it!")); } } else { AfxMessageBox(_T("Failed to query MySQL service status!")); } CloseServiceHandle(hService); } CloseServiceHandle(hSCM); } // 檢查連接端口是否正常 if (IsPortOpened(SERVERNAME, PORT) == FALSE) { AfxMessageBox(_T("MySQL port is not opened, please check firewall or network settings!")); }
3. 數據連接字符串有誤
// 確保服務器地址、用戶名、密碼、數據庫名、端口號等連接參數正確 CString sDsn; sDsn.Format(_T("ODBC;DRIVER={MySQL ODBC 5.3 ANSI Driver};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s;PORT=%d"), SERVERNAME, USERNAME, PASSWORD, DATABASE, PORT);
以上是我在解決 MFC 連接 MySQL 數據庫無法成功的過程中總結的一些可能出現的問題,僅供參考!