1、odb 下载地址 https://www.codesynthesis.com/products/odb/download.xhtml, 选择 Common Runtime Library -> libodb-2.4.0 ,Database Runtime Libraries -> libodb-mysql-2.4.0
2、下载 依赖库 https://www.codesynthesis.com/projects/libcutl/ , libcutl-1.10.0
3、先安装libcutl-1.10.0,进入目录执行 ./configure ; make ; make install;
4、再安装 libodb-2.4.0, 进入目录执行 ./configure ; make ; make install;
5、最后安装 libodb-mysql-2.4.0, 进入目录执行 ./configure ; make ; make install; 如果报缺少libmysql.._r字眼的错,sudo apt-get install libmysqld-dev就可以了;
6、使用
6.1、准备,创建person.hxx文件
#include <string>
#include <odb/core.hxx>
using namespace std;
#pragma db object no_id
class person
{
public:
friend class odb::access;
public:
unsigned long id;
string name;
string sex;
unsigned short age;
};
6.2、生成文文件,执行如下命令
odb -d mysql --generate-query --generate-schema person.hxx
运行这条语句会生成会生成四个文件,如下person-odb.cxx,person-odb.hxx,person-odb.ixx ,person.sql;person.sql是自动生成的建立表的sql语句。其他三个是操作数据库支持的代码;--generate-query选项是生成数据查询支持的代码,--generate-schema选项是生成创建数据表相关的代码。
6.3、编译使用demo
#include <iostream>
#include <odb/database.hxx>
#include <odb/transaction.hxx>
#include <odb/mysql/database.hxx>
#include "person-odb.hxx"
using namespace std;
using namespace odb::core;
int main (int argc, char* argv[])
{
person aben, wenhao;
aben.id = 1;
aben.name = "aben";
aben.sex = "man";
aben.age = 23;
wenhao.id = 2;
wenhao.name = "wenhao";
wenhao.sex = "man";
wenhao.age = 22;
typedef odb::query<person> query;
typedef odb::result<person> result;
try
{
shared_ptr<odb::mysql::database> db;
db.reset(new odb::mysql::database ("root", "12345", "test"));
transaction t (db->begin ());
t.tracer (stderr_tracer);
db->persist (aben);
db->persist (wenhao);
query q(query::id == 2);
result r = db->query<person>(q);
for (auto i:r)
{
cout << "{id:" << i.id << " name:" << i.name << " sex:" << i.sex << " age:" << i.age << "}" << endl;
}
t.commit ();
}
catch (const odb::exception& e)
{
cerr << e.what () << endl;
}
return 0;
}
编译 g++ -std=c++11 -o driver test.cpp person-odb.cxx -I ./ -L /usr/local/lib/ -lodb-mysql -lodb -lcutl
可参考 https://blog.csdn.net/woaichanganba/article/details/79841356