在 Visual Studio 中调用 mysql_real_connect() 函数连接 MySQL 过程中,当仅有连接 IP 错误时,会存在大概 20 秒的连接超时,最后连接失败;当有连接端口错误时,会存在大概 60 秒连接超时,最后连接失败。
通过在 mysql_real_connect() 前配置以下函数:
mysql_options(handle, MYSQL_OPT_CONNECT_TIMEOUT, timeOut)
但并不能成功在超时时间之后,结束连接请求。
这里提供一种线程解决方案,如下:
1 struct MySqlConnOpts_t 2 { 3 MYSQL* pConnHandle; 4 std::string strIp; 5 std::string strUserName; 6 std::string strPassWord; 7 int nPort; 8 int nErrNum; 9 10 MySqlConnOpts_t() 11 { 12 pConnHandle = NULL; 13 strIp = ""; 14 strUserName = ""; 15 strPassWord = ""; 16 nPort = -1; 17 nErrNum = -1; 18 } 19 }; 20 21 MySqlConnOpts_t* pConnectOptions = new MySqlConnOpts_t; 22 23 if(NULL != pConnectOptions) 24 { 25 // 进行 pConnectOptions 中 pConnHandle、strIp、strUserName、strPassWord、nPort 的配置操作; 26 } 27 else 28 { 29 // 内存申请失败操作; 30 } 31 32 33 DWORD WINAPI mysqlConnect(LPVOID lpParam) 34 { 35 DWORD ret = 0; 36 MySqlConnOpts_t* pConnOpts = static_cast<MySqlConnOpts_t*>(lpParam); 37 38 if(NULL == mysql_real_connect(pConnOpts->pConnHandle, pConnOpts->strIp , pConnOpts->strUserName, pConnOpts->strPassWord, pConnOpts->nPort, NULL, CLIENT_MULTI_STATEMENTS)) 39 { 40 ret = -1; 41 } 42 43 pConnOpts->nErrNum = ret; 44 45 return ret; 46 } 47 48 const int nTimeOut = 1000; // 超时设置,单位为 ms; 49 HANDLE hThread = CreateThread(NULL, 0, mysqlConnect, pConnectOptions, 0, NULL); 50 DWORD dwRet = WaitForSingleObject(hThread, nTimeOut); 51 CloseHandle(hThread); 52 53 if(0 != dwRet) 54 { 55 // 处理超时逻辑; 56 } 57 58 if(0 != pConnectOptions->nErrNum) 59 { 60 // 处理错误连接逻辑 61 } 62 63 // 处理 pConnectOptions 指针;
可以解决连接超时问题。