Evan
Evan

Reputation: 98

How to check if mysql query was successful using C++

I'm using a C++ interpreter (ROOT, the CERN framework) to access several mySQL tables in a loop. Every time I query a table that doesn't exist, the program quits on me:

for (int run = 19000; run < 22000; run ++) {
    s << run;
    num = s.str();
    schema = "run_0"+num+"_R007";
    s.str("");

    //creating our query
    query = "select distinct *whatever* from "+schema+".kTrack;";
    res = conPtr->Query(query);
    conPtr->Close();
    //Here is where I don't know what to do:
    if (*success*) {
        do stuff
    }
    else {
        do stuff
    }
}

I don't have a problem if the table returns 0 rows, I have a problem if the table doesn't exist.

What is wrong with my code?

Upvotes: 1

Views: 836

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596256

Assuming conPtr is a pointer to a TMySQLServer object, ROOT's documentation for TMySQLServer::Query() says:

Returns a pointer to a TSQLResult object if successful, 0 otherwise. The result object must be deleted by the user.

So Query() returns a NULL pointer on failure.

Also, since your loop is not re-opening a new DB connection on each iteration, you should not be calling conPtr->Close() until after you are done performing queries with it.

Try something more like this:

for (int run = 19000; run < 22000; run ++) {
    s << run;
    num = s.str();
    schema = "run_0"+num+"_R007";
    s.str("");

    //creating our query
    query = "select distinct *whatever* from "+schema+".kTrack;";
    res = conPtr->Query(query);
    if (res) {
        // use res as needed...
        delete res;
    }
    else {
        // ...
    }
}
conPtr->Close();

Upvotes: 1

Related Questions