c++ - mysqlpp 连接方法超时 - 我怎样才能控制它?

标签 c++ mysql database-connection mysql++

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

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

我需要处理的场景是数据库消失了,我的服务器必须处理这个问题。我当前的处理方式是对服务器执行 ping 操作,如果我发现 ping 失败,我将暂停查询 100 秒。之后我尝试重新建立连接。问题是,如果数据库仍然死掉,那么 connect 方法大约需要 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/

相关文章:

c++ - OpenCV 窗口卡住

c# - 如何在内部网中连接到 Access 上的数据库

linux - ubuntu 拒绝 postgres 连接

sql-server - 最大连接池大小

c++ - 为什么在某些机器上堆栈溢出,但在另一台机器上出现段错误?

c++ - 跟随恒定背景中的物体

android - 如何调试 Android/GDB/Qt 问题?

java - 合并具有相同结构和 Hibernate 映射的两个数据库

php - SQL查询条件不起作用

mysql - 查找重复的 mysql 最多位数