我试图从我的项目中的"Server“类实现mysql c-connector中的函数。下面是类构造函数的样子:(数据库和套接字都是#定义的)。
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;
}发布于 2019-04-18 11:24:52
在您的类函数定义中,您将调用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) {只需删除第一行,它就可以正常工作。
https://stackoverflow.com/questions/55738628
复制相似问题