2017-01-09 69 views
0

我正在测试一些与我的C代码集成的mysql。我注意到,如果mydomain.com在二进制运行时不可用,它会停留多于2分钟。我想避免这种情况,并设置最多5秒的超时时间。我怎样才能做到这一点?如何在C代码中减少MySQL连接超时

#include <my_global.h> 
#include <mysql.h> 

int main() { 

    MYSQL *con = mysql_init(NULL); 

    if (con == NULL) { 
     fprintf(stderr, "%s\n", "debug: could not initialize database"); 
     exit(1); 
    } 

    if (mysql_real_connect(con, "mydomain.com", "testuser", 
      "testuserpwd", "db_test", 0, NULL, 0) == NULL) { 
     exit(1); 
    } 
    ... 
    mysql_close(con); 

} 
+3

它被记录在手册中:http://dev.mysql.com/doc/refman/5.7/en/mysql-options.html –

+1

哦!我认为在证明'con == NULL'后'mysql_error(con)'不好。如果你不能初始化MySQL,那么它不是mysql的错误,因此,到目前为止,mysql会知道什么是“没有错误”。 –

+0

此外,[阅读此篇文章](http://stackoverflow.com/a/2213644/1983495) –

回答

0

这里的代码,因为它的工作原理。如果服务器不可用,timout现在是5秒i.s.o. 2分钟。

感谢您的帮助!

#include <my_global.h> 
#include <mysql.h> 

int main() { 

    MYSQL *con = mysql_init(NULL); 
    unsigned int mysql_ct; 

    mysql_ct = 5; 

    if (con == NULL) { 
     fprintf(stderr, "%s\n", "debug: could not initialize database"); 
     exit(1); 
    } 

    if (mysql_options(mysql_con, MYSQL_OPT_CONNECT_TIMEOUT, &mysql_ct)) { 
     fprintf(stderr, "debug (mysql): [mysql_options] failed."); 
    } 

    if (mysql_real_connect(con, "mydomain.com", "testuser", 
      "testuserpwd", "db_test", 0, NULL, 0) == NULL) { 
     exit(1); 
    } 
    ... 
    mysql_close(con); 

}