c++exceptionmysql-error-1062

Catch MySQL error in c++


In C++, I am using mysql.h libraries and I do not manage to catch MySQL errors (for example, failure to insert due to conflict in primary key).

I have tried

#include <mysql.h>
// ...
try{
    res = mysql_perform_query(conn, sqlIn);
} catch (...) {
// ...
}

but it still does not avoid aborting with:

MySQL query error : Duplicate entry

I am running the compiled c++ program using PuTTy interface and as the program aborts, it reproduces MySQL's error (regardless of whether I use TRY CATCH or not).
I have not found any reference to specific exception codes for MySQL use with catch statement.

Apparently, C++ (using this library mysql.h) does not catch MySQL callback errors even with the "blanket" syntax (catch (...)). Since this syntax should catch ALL exceptions, yet doesn't in this case, I am at a loss to understand what is happening here. How can I catch the SQL exceptions?


Solution

  • The mysql C library does not throw any excptions; it merely, like most other C libraries, sets up error info in a common place ( like errno ) and returns a status. Its up to your client code to check the return and throw an error/exception.

    If you need an easy fix for your problem, try mysql++ (AKA mysqlpp). It is a piece of software that I can vouch for; solid as a rock! http://tangentsoft.net/mysql++/