0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But why can't it ignore the second connection though ? previously, I couldn't execute mysql_close(&san). it gave me bus error. Could you please explain it ?
@Vasanth hard to say without looking at the internals of the MySQL API code, but I guess that's just not the way the interface is designed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.