我正在使用mysql c++ connector。我想连接到我的数据库,如果连接消失,继续连接并重新连接。
这是一个连接代码:
driver = sql::mysql::get_driver_instance();
connection = driver->connect(Server, UserID, Password);
here它表示方法connection-> isValid()和reconnect()可以知道连接是否处于活动状态,如果不存在则重新连接。所以我想这个:
bool MySqlCommunicator::Connect()
{
try
{
bool connected = connection != NULL && (connection->isValid() || connection->reconnect());
if (!connected)
{
connection = driver->connect(Server, UserID, Password);
connected = connection->isValid();
}
if (connected)
{
statement = connection->createStatement();
char str[255];
sprintf(str, "USE %s", Database);
statement->execute(str);
return true;
}
return false;
}
catch (sql::SQLException &e)
{
delete connection;
connection = NULL;
return false;
}
}
然后每次我想执行查询时,我都会调用Connect()来确保连接准备就绪。我假设如果连接不活动,Connect()方法将重新连接。
但是当到达此行时程序崩溃:
bool connected = connection != NULL && (connection->isValid() || connection->reconnect());
它无法执行isValid()方法,程序退出时出现消息分段错误。
好吧,我将代码更改为以下内容:
bool MySqlCommunicator::Connect()
{
try
{
bool connected = connection != NULL; //connection != NULL && (connection->isValid() || connection->reconnect());
if (!connected)
{
connection = driver->connect(Server, UserID, Password);
//connected = connection->isValid();
connected = true;
}
if (connected)
{
statement = connection->createStatement();
char str[255];
sprintf(str, "USE %s", Database);
statement->execute(str);
return true;
}
return false;
}
catch (sql::SQLException &e)
{
delete connection;
connection = NULL;
return false;
}
}
现在它有效!如果发生任何错误,它将重新连接以使其正确。但这不是解决方案!我想要一个合适的解决方案。
(等待有人回答!提前谢谢)
答案 0 :(得分:2)
我的最终工作代码是:
bool MySqlCommunicator::Connect()
{
try
{
bool connected = connection != NULL && (connection->isValid() || connection->reconnect());
if (!connected)
{
connection = driver->connect(Server, UserID, Password);
connected = connection->isValid();
}
if (connected)
{
//connection->setReadOnly(false);
statement = connection->createStatement();
char str[255];
sprintf(str, "USE %s", Database);
statement->execute(str);
return true;
}
return false;
}
catch (sql::SQLException &e)
{
delete connection;
connection = NULL;
return false;
}
}