Reputation: 119
I was trying to implement the functions in mysql c-connector from the class "Server" in my project. Here is how the class constructor looks like: (DATABASE and SOCKET are #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;
}
}
When I try calling the class from "main.cpp" with the connection handle, it causes an error.
Cannot connect twice. Already connected.
but if the methods were written outside the class, it runs flawlessly. Basically, this works.
#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;
}
But this doesn't and fails with aforementioned error.
#include "Server.hxx"
MYSQL san;
int main(int argc, char** argv)
{
Server S0(san);
return 0;
}
Upvotes: 0
Views: 77
Reputation: 147166
In your class function definition you are calling mysql_real_connect
twice:
mysql_real_connect(&conn,"localhost","username","passwd",DATABASE,0,SOCKET,0);
if (mysql_real_connect(&conn,"localhost","santu","hello",DATABASE,0,SOCKET,0) == NULL) {
Just remove the first line and it will work fine.
Upvotes: 1