根据 kingstonian 的建议,我在 mysql 周围使用了 mysql++ 包装器(要在 ubuntu 中安装,请参阅我的回答另一个 SO 问题的食谱)
下面的代码用于测试错误处理,其中在键中插入了重复值 (Id_Target = 9)。使用适合您的数据库结构的插入来适应您自己的需求。
#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;
}
}