在这篇文章 http://www.maycode.com/index.php/linux/54-linuxdevelop/1192-mysql.html 我们介绍了mysql connector/c++ ,本文中我们简单介绍一下安装和使用过程。
要安装mysql connector/c++ 首先要安装cmake,cmake 是一个跨平台的build工具,在linux下可以构建出makefile,然后做编译,在google上有很多cmake的文章。
1、安装cmake
wget http://www.cmake.org/files/v2.6/cmake-2.6.2.tar.gz
tar -xvzf cmake-2.6.2.tar.gz
cd cmake-2.6.2
./bootstrap; make; make install
这样就安装完毕了最新版本的cmake
2、安装mysql connector/c++
wget http://downloads.mysql.com/forge/connector_cpp_preview/mysql_connector_cpp_1_0_0_preview.tar.gz
tar -xvzf mysql_connector_cpp_1_0_0_preview.tar.gz
cd mysql_connector_cpp_1_0_0_preview
cmake -L
你可以检查各个目录设置是否正确
然后cmake 就编译完成了
生成的so在cppconn目录下,在example下面有使用的例子。
3、验证使用
以下是一个简单使用的例子:
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include "cppconn/mysql_public_iface.h"
static void validateRow(sql::ResultSet *res, struct _test_data *exp);
using namespace std;
int main()
{
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
cout << "Connector/C++ result set.." << endl << endl;
try {
driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect("127.0.0.1", "3306","root", "password");
stmt = con->createStatement();
stmt->execute("USE " "lovebase");
stmt->execute("DROP TABLE IF EXISTS test");
stmt->execute("CREATE TABLE test(id INT, label CHAR(1))");
stmt->execute("INSERT INTO test(id, label) VALUES (1, 'a')");
cout << "\tTest table created" << endl;
cout << "done!" << endl;
} catch (sql::mysql::MySQL_DbcException *e) {
cout << endl;
delete e;
return EXIT_FAILURE;
} catch (sql::DbcException *e) {
cout << endl;
delete e;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
注意代码中的用户名,密码和数据库要改成你自己的设置。
因为还不习惯cmake,而例子中都是使用cmake做的相应配置,我给出一个g++编译的命令:
g++ -I ../ -I ../cppconn/ -I /usr/local/mysql/include/ -L /usr/local/mysql/lib/ -L ../cppconn/ -lmysqlclient -lmysqlcppconn -o test test.cc
test.cc 在examples目录下,如果在你的机器上肯定要做相关的修改。
接下来就可以运行了,注意设置一下LD_LIBRARY_PATH
比如在我机器上:LD_LIBRARY_PATH=/root/mysql_connector_cpp_1_0_0_preview/cppconn/
就可以./test 了,运行你可以看到相应的数据库中建立了test表。