gpt4 book ai didi

c++ - mysql c++ 连接器,如果连接断开,如何保持连接并重新连接?

转载 作者:行者123 更新时间:2023-11-29 06:21:42 25 4
gpt4 key购买 nike

我正在使用 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;
}
}

现在可以了!如果发生任何错误,它将重新连接以使其正确。但这不是解决方案!我想要一个合适的解决方案。

  • 为什么我的第一个代码在提到的行上崩溃了?
  • 其他方法如connection->setReadOnly() 也会使程序崩溃!是什么原因造成的?
  • 确保连接有效的最佳方法是什么?
  • 在出现错误时重新连接到远程数据库的最佳做法是什么?

(等待有人回答!提前致谢)

最佳答案

经过数小时的挖掘,我找到了解决方案。我交叉编译了更新版本的 mysql c++ 连接器,并用它来编译和运行我的代码。现在方法 isValid() 和 reconnect() 正在工作。 (setreadOnly()方法好像还没有实现)。

我的最终工作代码是:

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;
}

}

关于c++ - mysql c++ 连接器,如果连接断开,如何保持连接并重新连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003635/

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