我在终止使用 MYSQL C++ Connector 1.1.3 创建的 MYSQL 连接时遇到困难
sql::Connection *con;
/* Creating Connection */
//....
/* Executing Statements */
//..
con->close(); // This should terminate the TCP Connection
但即使在调用 close() 函数后,与 MYSQL 服务器的 TCP 连接也不会终止。它只会在应用程序进程终止后断开连接。
仔细查看后,我发现了以下内容:
1>
//checkedclosed() function of MySQL_Connection Class
if (!intern->is_valid) { // returns true
throw sql::SQLException("Connection has been closed");
2>
MySQL_Connection::clearWarnings()
{
CPP_ENTER_WL(intern->logger, "MySQL_Connection::clearWarnings");
// intern closed = false
intern->warnings.reset();
}
请指导我如何终止 MYSQL 连接。
更新:
class MySqlConn
{
private:
sql::Driver *driver;
sql::Connection *con;
public:
bool initDBConnection();
bool CloseDBConnection();
};
bool MySqlConn::initDBConnection()
{
this->driver = get_driver_instance();
try
{
this->con = this->driver->connect(HOST, USER, PASS);
this->con->setSchema(DB);
return true;
}
catch(sql::SQLException &e)
{
CLogger::LogEvent("Failed TO Connect to DataBase Server" ,e.what());
return false;
}
}
bool MySqlConn::CloseDBConnection()
{
try
{
this->conn->close();
return true;
}
catch(sql::SQLException &e)
{
CLogger::LogEvent("Failed To Close Connection to DataBase Server" ,e.what());
return false;
}
}
void someclass::somefunc()
{
MySqlConn db_conn;
if(db_conn.initDBConnection())
{
//Do Somthing
db_conn.CloseDBConnection();
}
}
所以,我想在这种情况下我不必调用析构函数,因为一旦 someclass::somefunc() 的作用域结束,对象本身就会被析构?
最佳答案
已解决:
最终这是一个简单的解决方案。
bool MySqlConn::CloseDBConnection()
{
try
{
this->con->close();
delete this->con;
this->driver->threadEnd();
return true;
}
catch(sql::SQLException &e)
{
CLogger::LogEvent("Failed To Close Connection to DataBase Server" ,e.what());
return false;
}
}
现在连接从 ESTABLISHED 转到 TIME_WAIT,这意味着连接已从这一端终止,并等待从另一端重新发送任何损坏的帧。等待时间结束后,TCP 连接终止。
问候
Gencoide_Hoax
关于C++ MySQL 连接器无法断开 sql::Connection close() 调用上的 TCP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18600237/