安装依赖:
yum install boost
yum install boost-devel
yum install boost-doc
yum install mysql-devel
下载Connector/C++库:
CentOS6 32位下载解压得到里面的库文件和头文件。
编写测试代码:
#include <cstdlib>
#include <iostream>
#include <string.h>
#include "mysql_connection.h"
#include "mysql_driver.h"
#include "driver.h"
#include "statement.h"
using namespace std;
using namespace sql;
int main(int argc, char** argv) {
Driver *driver;
Connection *conn;
Statement *state;
ResultSet *result;
driver = get_driver_instance();
conn = driver->connect("tcp://localhost:3306", "root", "123456");
state = conn->createStatement();
state->execute("use lpvote1");
result = state->executeQuery("select * from topic_class");
for(; result->next();){
cout << result->getString("TopicClassName") << endl;
}
state->close();
conn->close();
delete result;
delete state;
delete conn;
return 0;
}
编译选项:
-I 指定头文件路径,-L 指定库文件路径,-l 指定库文件,还需要添加 `mysql_config --cflags --libs`,不然报函数未定义的错误。
用起来就跟jdbc一样,封装的真好。我曾经研究过OCI(Oracle call Interface),用起来太麻烦,内存管理很复杂。