3

我在终止使用 MYSQL C++ 连接器 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() 的范围结束,对象本身就会被破坏?

4

2 回答 2

5

解决了:

最后这是一个简单的解决方案。

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

于 2013-09-07T11:10:53.260 回答
0

您必须确保关闭所有对象并删除连接:

res->close();
stmt->close();

con->close();

delete BD_con;

driver->threadEnd();
于 2015-06-15T01:07:43.120 回答