所以可以使用
//&是你自己初始化的数据库名字
//&time=3表示3秒连接不上,直接报错
int time=3;
int ret=mysql_optios(&mysql,MYSQL_OPT_TIMEOUT,&time);
//如果没有连接上,汇报原因
//mysql_error(&mysql)
if (ret != 0)
{
//失败
std::cout << "mysql_options failed!" << mysql_error(&mysql);
}
int reconnect=1;
mysql_options(&mysql,MYSQL_OPT_RECONNECT,&reconnect);
测试代码,
mysql_ping(&mysql)
如果ping到的话,输出成功,ping不到输出失败以及原因
this.thread:sleep_for(1s);//1s ping一次
//mysql_options断开重连
for (int i=0;i<1000;i++)
{
int ret = mysql_ping(&mysql);
if (ret == 0)
{
//成功
cout << host << ":mysql ping success!" << endl;
}
else
{
cout << host << ":mysql ping failed!" <<mysql_error(&mysql) << endl;
}
this_thread::sleep_for(1s);//1s ping一次
}
3、整体代码
#include<iostream>
#include<stdio.h>
#include<mysql.h>
#include<thread>//释放当前的cpu
using namespace std;
int main()
{
MYSQL mysql;
mysql_init(&mysql);
//连接登录数据库
const char* host = "127.0.0.1";
//const char* host = "198.168.0.233"; //随便起的,判断链接出错会花费好久
const char* user = "root";
const char* password = "990107Wjl@";
const char* database_name = "database_test";
const int port = 3306;
//设定超时3秒
int to = 3;
int ret=mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, &to);//设置3秒,立刻返回,就不用浪费那么多时间了
if (ret != 0)
{
//失败
std::cout << "mysql_options failed!" << mysql_error(&mysql);
}
int recon = 1;
ret = mysql_options(&mysql, MYSQL_OPT_RECONNECT, &recon);
//如果没有连接上
if (!mysql_real_connect(&mysql, host, user, password, database_name, port, NULL, 0))
{
//fprintf(stderr, mysql_error(&mysql));
std::cout << "mysql connect failed!" << mysql_error(&mysql);
}
else
{
std::cout << "mysql connect " << host << "successfully!" << std::endl;
}
//mysql_options断开重连
for (int i=0;i<1000;i++)
{
int ret = mysql_ping(&mysql);
if (ret == 0)
{
//成功
cout << host << ":mysql ping success!" << endl;
}
else
{
cout << host << ":mysql ping failed!" <<mysql_error(&mysql) << endl;
}
this_thread::sleep_for(1s);//1s ping一次
}
system("pause");
return 0;
}
4、具体实验视频如下
MySQL数据库连接超时和自动ping