1.下載ODB library:ODB Compiler,Common Runtime Library,Database Runtime Library。
http://www.codesynthesis.com/products/odb/download.xhtml(注意:ODB Compiler為odb-x.x.x-i686-windows, Database Runtime Libraries為你想要用的資料庫對應的庫)2.解壓,安裝 你可以在根目錄執行odb,也可以加到環境變數裡。 3.標頭檔中定義類,上邊為正常類,下邊為修改為odb的persistent 類
class person { ... private: string email_; string name_; unsigned short age_; };
#include <string>
#include <odb/core.hxx>
#pragma db object class person { ... private: friend class odb::access; person () {} #pragma db id string email_; string name_; unsigned short age_; };
4.利用odb產生資料庫支援代碼,只有這樣子才能利用上面定義的persistent類進行查詢。具體命令列參數:http://www.codesynthesis.com/products/odb/doc/odb.xhtml如:odb --database mysql --generate-query D:\MCSF_Backup\MAIN\Features\McsfProtocolDBWrapper\McsfProtocolDBWrapper\include\catalog.hxx產生5.添加產生的3個檔案到工程裡,使用。 如Insert:
#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;intmain (int argc, char* argv[]){ try { auto_ptr<database> db (new odb::mysql::database (argc, argv)); unsigned long john_id, jane_id, joe_id; // Create a few persistent person objects. // { person john ("John", "Doe", 33); person jane ("Jane", "Doe", 32); person joe ("Joe", "Dirt", 30); transaction t (db->begin ()); // Make objects persistent and save their ids for later use. // john_id = db->persist (john); jane_id = db->persist (jane); joe_id = db->persist (joe); t.commit (); } } catch (const odb::exception& e) { cerr << e.what () << endl; return 1; }}
6.注意:在定義的persistent 類中, 有幾個#pragma經常使用。1)指定欄位為主鍵: #pragma db id2) 指定欄位為資料庫相應類型:#pragma db type("VARCHAR(64) binary not null")3)指定欄位為資料庫相應的列:#pragma db column("CatalogName")4)指定資料庫的主鍵自增長: #pragma db id auto
在用odb產生資料庫支援代碼時,有時候persistent類中引用了別的庫, 在編譯時間可以通過-I添加路徑。
比如: