在类中定义时,mysql C连接器函数不起作用

时间:2019-04-18 03:13:30

标签: c++ mysql c++11

我试图从我的项目中的“服务器”类实现mysql c-connector中的功能。这是类构造函数的外观: (DATABASE和SOCKET是#defined)。

Server::Server(MYSQL& conn)
{
    mysql_init(&conn);
    mysql_real_connect(&conn,"localhost","username","passwd",DATABASE,0,SOCKET,0);
    if (mysql_real_connect(&conn,"localhost","santu","hello",DATABASE,0,SOCKET,0) == NULL) {
        cout << mysql_error(&conn) << endl;
    }
    else
    {
        cout << "Connected." << endl;
    }
}

当我尝试使用连接句柄从“ main.cpp”调用该类时,会导致错误。

Cannot connect twice. Already connected.

但是,如果方法是在类外部编写的,则它可以完美运行。基本上,这可行。

#include "Server.hxx"

MYSQL san;

int main(int argc, char** argv)
{
    mysql_init(&san);
    mysql_real_connect(&san,"localhost","santu","hello", "test",0,"/tmp/mysql.sock",0);
    cout << mysql_error(&san) << endl;
    return 0;
}

但这不是,并且由于上述错误而失败。

#include "Server.hxx"

MYSQL san;

int main(int argc, char** argv)
{
    Server S0(san);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

在类函数定义中,您两次调用mysql_real_connect

mysql_real_connect(&conn,"localhost","username","passwd",DATABASE,0,SOCKET,0);
if (mysql_real_connect(&conn,"localhost","santu","hello",DATABASE,0,SOCKET,0) == NULL) {

只需删除第一行,它将正常工作。