C ++ MySQL连接器无法在sql :: Connection close()调用上断开TCP连接

时间:2013-09-03 19:42:05

标签: c++ mysql visual-c++ tcp mysql-connector

我无法终止使用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()的范围结束,对象本身就会被破坏?

2 个答案:

答案 0 :(得分:4)

<强>解决:

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

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

}

现在Connection从ESTABLISHED转到TIME_WAIT,这意味着连接已从此端终止,并等待任何损坏的帧从另一端重新发送。在WAIT时间结束后,TCP连接终止。

<强>此致

<强> Gencoide_Hoax

答案 1 :(得分:0)

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

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

con->close();

delete BD_con;

driver->threadEnd();