处理MySQL C ++连接器上丢失的TCP连接

时间:2014-05-26 00:24:52

标签: c++ mysql

如何处理MySQL C ++连接器上丢失的TCP连接?

我的代码大致如下:

sql::Driver* driver = get_driver_instance();
sql::Connection *con = driver->connect("tcp://host:3306", "user", "pass");
sql::PreparedStatement *pstmt = con->prepareStatement("INSERT INTO...");

...

// Set parameters
pstmt->setString(1, "hi");
pstmt->setInt(2, 123);
...

// Perform insertion
pstmt->executeUpdate();

程序无限期运行,// Set parameters// Perform insertion被多次调用。问题是如果TCP连接关闭(例如:因为mysql服务器重启/超时)插入失败:

# ERR: SQLException in ****.cpp(*****) on line 211
# ERR: Lost connection to MySQL server during query (MySQL error code: 2013, SQL
State: HY000 )

我尝试将OPT_RECONNECTMYSQL_OPT_RECONNECT选项设为true as suggested by this post,但这没有帮助

sql::Driver* driver = get_driver_instance();
sql::Connection *con = driver->connect("tcp://host:3306", "user", "pass");
bool myTrue = true;
con->setClientOption("MYSQL_OPT_RECONNECT", &myTrue); // Or "OPT_RECONNECT"

我尝试使用con->executeUpdate() con->isClosed()之前手动检查并重新连接,但仍然没有运气。即使TCP连接被终止,con->isClosed()也始终返回false。

我正在编译MySQL 5.6库。

1 个答案:

答案 0 :(得分:1)

我的解决方案是在使用之前使用SELECT 1之类的简单语句手动测试连接:

try {
  res = stmt->executeQuery("SELECT 1");
  delete res; res = NULL;
} catch(sql::SQLException& e) {
  // Connection is lost, reconnect..
  delete pstmt; delete con;
  con = driver->connect(..);
  pstmt = con->prepareStatement(..);
}

当连接丢失时,必须重新创建预准备的语句对象

使用3rd party connection pooling library such as libzdb建议的其他帖子。希望有更好的&更容易的选择