MySQL 连接中 IP 或端口错误导致连接超时的解决方案
时间:2021-07-01 10:21:17
帮助过:36人阅读
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 ret = -
1;
32 }
33
34 pConnOpts->nErrNum =
ret;
35
36 return ret;
37 }
38
39 const int nTimeOut =
1000;
// 超时设置,单位为 ms;
40 HANDLE hThread = CreateThread(NULL,
0, mysqlConnect, pConnectOptions,
0, NULL);
41 DWORD dwRet =
WaitForSingleObject(hThread, nTimeOut);
42 CloseHandle(hThread);
43
44 if(
0 !=
dwRet)
45 {
46 // 处理超时逻辑;
47 }
48
49 if(
0 != pConnectOptions->
nErrNum)
50 {
51 // 处理错误连接逻辑
52 }
53
54 // 处理 pConnectOptions 指针;
可以解决连接超时问题。
MySQL 连接中 IP 或端口错误导致连接超时的解决方案
标签:初始 word 方案 cli timeout class 连接超时 studio struct