Catch MySQL error in c++

限于喜欢 提交于 2019-12-06 15:11:35

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++/

Try using some c++ wrapper around the mysql C library. e.g. http://mysqlcppapi.sourceforge.net/

C doesnt throw exceptions you have to check via mysql_errorno function.

I wont suggest Mysql C++ libraries for two reasons 1.It is difficult to get support. 2.Slow compared to Mysql C library

you can use mysql_error() and mysql_errno() API's to know the errors and manually through exceptions

tony gil

as per kingstonian's suggestion, i used the mysql++ wrapper around mysql (for installation in ubuntu, see my recipe answering another SO question)

the code below was used to test error handling, where a duplicate value was inserted in the key (Id_Target = 9). adapt to your own needs, using the appropriate insert for your DB structure.

#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include </usr/include/mysql++/mysql++.h>


// sudo g++ -o /temp/zdelMySQLpp01c $(mysql_config --cflags) /home/ubuntu/zdelMySQLpp01c.cpp $(mysql_config --cflags --libs) -l pthread -std=c++0x -g -L/usr/lib/mysql -lmysqlclient -lmysqlpp

using namespace mysqlpp;
using namespace std;

//MySQL type
struct connection_details {
        char *server;
        char *user;
        char *password;
        char *database;
};

int main(int argv, char** argc){

// MySQL connection (global)
struct connection_details mysqlD;
mysqlD.server = (char *)"localhost";  // where the mysql database is
mysqlD.user = (char *)"root";       // the root user of mysql   
mysqlD.password = (char *)"XXXXXX"; // the password of the root user in mysql
mysqlD.database = (char *)"test";   // the databse to pick

// connect to the mysql database
mysqlpp::Connection conn(false);
if (conn.connect(mysqlD.database, mysqlD.server, mysqlD.user, mysqlD.password)) {
    //printf("ALOALO funcionou conexao\n");
    mysqlpp::Query query = conn.query("INSERT INTO test.target (Id_Target, Ds_Target, Ds_Target_Name, Ds_Target_PWD, Ds_Target_Email, Ds_Target_Icon) VALUES ('9', 'test', 'name', 'pass', 'email', NULL)");
        if (mysqlpp::StoreQueryResult res = query.store()) {
                cout << "We have:" << endl;
                for (size_t i = 0; i < res.num_rows(); ++i) {
                    cout << '\t' << res[i][0] << endl;
                }
        } else {
                cerr << "Failed to get item list: " << query.error() << endl;
                return 1;
    }
        return 0;
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!