mysql - 如何用C代码减少MySQL连接超时

标签 mysql c timeout

我正在测试一些 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 秒。 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);

}

关于mysql - 如何用C代码减少MySQL连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41550216/

相关文章:

c - 文件中的单词计数,如 C 中的 linux wc 命令

javascript - TypeScript setTimeout 循环传递此错误

Mysql主ID没有自动递增?

MySQL - 更新列中字符串的一部分

c - fork()后谁先执行 : parent or the child?

C - 浮点异常(核心转储)

c# - C#中SQL Server超时异常和SqlCommand超时异常的区别

erlang - 为什么 Pry shell 在 Phoenix/cowboy 中超时如此之快? (shell 进程退出的原因是 : shutdown)

mysql - 将一个表中的数据插入到另一个表中

php - 从 PHP 到 Laravel 的转换