gpt4 book ai didi

c++ - mysqlpp 连接方法超时 - 我如何控制它?

转载 作者:搜寻专家 更新时间:2023-10-31 01:19:10 24 4
gpt4 key购买 nike

我试图控制连接方法超时,但我没有找到合适的方法。

需要说明的是,我不是在谈论空闲连接超时 (ConnectTimeoutOption)。

我需要处理的场景是数据库消失了,我的服务器必须处理这个问题。我目前的处理方式是对服务器执行 ping 操作,如果发现 ping 操作失败,我会将查询暂停 100 秒。之后我试图重新建立连接。问题是,如果数据库仍然死机,那么连接方法需要大约 20 秒才能响应(可以通过拉网线来模拟),这对我来说太多了。

最佳答案

这应该适合你

#include <mysql++.h>
#include <cstdio>

int main()
{
mysqlpp::Connection conn;
conn.set_option(new mysqlpp::ReconnectOption(true));
conn.set_option(new mysqlpp::ConnectTimeoutOption(5));

const std::string db="mysql_cpp_data";
const std::string query_text="SELECT count(*) as total FROM stock";
conn.connect(db.c_str(), "somehost", "user", "pass");

try
{
mysqlpp::Query query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << std::endl;
}
std::cout << "Make database go away now and press a key\n";
getchar();

try
{
mysqlpp::Query query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << std::endl;
std::cout << "Make database come back now and press a key\n";
getchar();
while(!conn.ping())
{
sleep(1);
std::cout << "Waiting for DB to come back\n";
}
if(!conn.select_db(db))
{
std::cout << "Failed to change DB\n";
}
}

try
{
mysqlpp::Query query=conn.query();
query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << " " << e.errnum() << std::endl;
}

return 0;
}

关于c++ - mysqlpp 连接方法超时 - 我如何控制它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com