背景
最近一直在看odb官网上odb-manual,由于是全英文文档,仔细看过一遍之后虽然感觉基本了解,但是隔几天之后再翻开时又要逐一回忆当初理解的一些细节,毕竟不是母语,没有那种一看就条件反射式的想起来,所以把一些key word记录下来,避免下次重复花时间来消化知识。对于一个coder,能够用代码来阐述的,就尽量不用文字,所以在记录过程中尽量通过代码来展示一些api的用法。
使用说明
本文基于odb官方手册为指导,通过自己的理解之后用尽可能通俗易懂的文字来阐述相关用法。站在应用编程的角度,将文档中常用知识点、易错点进行翻译整理。同时本文也弱化掉了一些不常用的知识点,基于这种考虑主要是由于本文的立足点是为了使编程人员尽快上手开发,如果将一些不常用的知识点也罗列其中会显得繁杂且冗余,所以如果在开发过程中遇到本文未提及的点可以回到odb官方手册进行查询。
Hello World实例
-
声明持久化类
比如一个person.hxx类的头文件如下所示// person.hxx // #include <string> class person { public: person(const std::string& first, const std::string& last, unsigned short age); const std::string& first () const; const std::string& last () const; unsigned short age () const; void age (unsigned short); private: std::string first_; std::string last_; unsigned short age_; };
如果需要存储在数据库中,则需要将person类的声明部分进行改造,需要修改的地方有(1)(2)(3)(4)(5),修改后的声明如下:
// person.hxx // #include <odb/core.hxx> // (1) #include <string> #pragma db object // (2) class person { public: person(const std::string& first, const std::string& last, unsigned short age); const std::string& first () const; const std::string& last () const; unsigned short age () const; void age (unsigned short); private: person () { } // (3) friend class odb::access; // (4) #pragma db id auto // (5) unsigned long id_; // (5) std::string first_; std::string last_; unsigned short age_; };
-
产生odb的中间文件
odb -d mysql --generate-query person.hxx
如果需要mysql语句,则执行如下指令:
odb -d mysql --generate-query --generate-schema person.hxx
-
编译运行
如果是首次运行,需要在mysql数据库中将mysql语句文件导入其中,以此来生成数据库相关的表mysql --user=odb_test --database=odb_test < person.sql
-
创建持久化对象
源码如下:
// driver.cxx // #include <memory> // std::auto_ptr #include <iostream> #include <odb/database.hxx> #include <odb/transaction.hxx> #include <odb/mysql/database.hxx> #include "person.hxx" #include "person-odb.hxx" using namespace std; using namespace odb::core; int main (int argc, char* argv[]) { try { // mysql server's host name: root, password:123456, ip:198.1.17.252, port:30306 auto_ptr<database> db(new odb::mysql::database