Call in Visual Studio mysql_real_connect () function to connect MySQL process, when only the IP connection error, there is a connection timeout about 20 seconds, the last connection failure; when there is a connection port wrong, there will be about 60 seconds connection timeout, Finally, the connection fails.
By mysql_real_connect () before configuring the following functions:
mysql_options(handle, MYSQL_OPT_CONNECT_TIMEOUT, timeOut)
But it does not succeed after a timeout, the end of the connection request.
There is provided a process solution as follows:
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 // pConnectOptions 中 pConnHandle、strIp、strUserName、strPassWord、nPort 的初始化; 23 24 DWORD WINAPI mysqlConnect(LPVOID lpParam) 25 { 26 DWORD ret = 0; 27 MySqlConnOpts_t* pConnOpts = static_cast<MySqlConnOpts_t*>(lpParam); 28 29 IF (== NULL mysql_real_connect (pConnOpts-> pConnHandle, pConnOpts-> strIp, pConnOpts-> strUserName, pConnOpts-> strPassword, pConnOpts-> nPort, NULL, CLIENT_MULTI_STATEMENTS)) 30 { 31 is RET = - . 1 ; 32 } 33 is 34 is pConnOpts -> = nErrNum RET; 35 36 return RET; 37 [ } 38 is 39 const int nTimeOut = 1000 ; // timeout setting unit MS; 40 HANDLE = hThread the CreateThread (NULL, 0 , mysqlconnect, pConnectOptions, 0, NULL); 41 is DWORD = dwRet the WaitForSingleObject (hThread, nTimeOut); 42 is the CloseHandle (hThread); 43 is 44 is IF ( 0 ! = DwRet) 45 { 46 is // process timeout logic; 47 } 48 49 IF ( 0 ! = PConnectOptions- > nErrNum) 50 { 51 is // processing error connection logic 52 } 53 is 54 is // process pConnectOptions pointer;
Connection timeout problem can be solved.