我正在测试一些 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/