如何减少 C 代码中的 MySQL 连接超时

How to reduce MySQL connection timeout in C code

我正在测试一些 mysql 与我的 C 代码的集成。我注意到如果 mydomain.com 在二进制文件运行时不可用,它会卡住 2 分钟多一点。我想避免这种情况并设置最长 5 秒的超时。我该怎么做?

#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);

}

此处的代码按预期工作。如果服务器不可用,超时现在是 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);

}