標籤:串連資料庫 unsigned title 相關 標識 sig tmp product das
摘要: 2、使用 首先,需要定義一個對象,用來和資料庫欄位對應: [cce lang=”cpp”] #ifndef VOLUME_H #define VOLUME_H #include #include #pragma db object cl
2、使用
首先,需要定義一個對象,用來和資料庫欄位對應:
[cce lang=”cpp”]
#ifndef VOLUME_H
#define VOLUME_H
#include <string>
#include <odb/core.hxx>
#pragma db object
class Volume
{
public:
Volume(const std::string &name, const std::string &location, const std::string &cover_path, int trackCount)
: _name(name), _location(location), _cover_path(cover_path), _trackerCount(trackCount)
{}
unsigned long long id() { return _id; }
void id(unsigned long long i) { _id = i;}
const std::string &name() {return _name;}
void name(const std::string &n) {_name = n;}
const std::string &location() {return _location;}
void location(const std::string &l) {_location = l;}
const std::string &cover_path() {return _cover_path;}
void cover_path(const std::string &c) {_cover_path = c;}
int trackCount() {return _trackerCount;}
void trackCount(int c) {_trackerCount = c;}
private:
friend class odb::access;
Volume () {}
#pragma db id auto
unsigned long long _id;
std::string _name;
std::string _location;
std::string _cover_path;
int _trackerCount;
};
[/cce]
首先是引入core.hxx這個標頭檔,包含access這個類。在類上面添加#pragma db object宏,標識這是個資料庫物件。在主鍵上增加宏#pragma db id auto,標識這個是主鍵,並且自增。這兩個宏都是提供資訊給odb,用來產生最終c++代碼的。因為資料庫對應欄位都是私人類型,所以需要將odb::access聲明為友元。
為了方便,這裡串連資料庫都使用sqlite,因此,需要引入sqlite相關的包。建立資料庫連接(對sqlite來說,就是開啟資料庫檔案):
[cce lang=”cpp”]
std::shared_ptr<odb::database> sqliteDB(new odb::sqlite::database("mycppweb.db", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE));
[/cce]
註:這裡需要引入標頭檔odb/sqlite/database.hxx,建立資料庫連接的第一個參數(只針對sqlite)是資料庫檔案名,後面是開啟的flag,這裡主要是提示如果資料庫檔案不存在,預設建立。另外,這裡使用了c++11的shared_ptr,g++需要添加參數-std=c++0x
插入對象:
[cce lang=”cpp”]
{
odb::transaction t(db->begin());
volumeId = db->persist(volume);
t.commit();
}
[/cce]
插入的時候,使用了事務,需要引入odb/transaction.hxx標頭檔,並且盡量減少transaction的生命週期。
通過odb命令產生對應的代碼:
[cce lang=”bash”]
odb –database sqlite \
–hxx-suffix .hpp –ixx-suffix .ipp –cxx-suffix .cpp \
–output-dir /tmp \
–generate-query –generate-schema –schema-format embedded volume.h
[/cce]
這裡指定輸出的資料庫是sqlite,建立schema的語句嵌入到代碼裡面。
執行之後,會產生volume-odb.hpp、volume-odb.cpp和volume-odb.ipp三個檔案。查看volume-odb.cpp就會發現,裡麵包含了volume.h中指定的類和資料庫表的關係。如果希望通過代碼來建立資料庫(貌似需要自己來判斷是否已經存在,否則第二次運行又會重新建立表,導致資料丟失),可以通過:
[cce lang=”cpp”]
{
odb::transaction t (sqliteDB->begin ());
odb::schema_catalog::create_schema (*sqliteDB);
t.commit ();
}
[/cce]
odb的查詢,還沒有去嘗試,具體文檔在http://www.codesynthesis.com/products/odb/doc/manual.xhtml
ODB——基於c++的ORM映射架構嘗試(使用)