如何使用ODB(How to use odb On windows)

1.下载ODB library:ODB Compiler,Common Runtime Library,Database Runtime Library。


(注意: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

如:


生成


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;

int
main (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 id
2)  指定字段为数据库相应类型:#pragma db type("VARCHAR(64) binary not null")
3)指定字段为数据库相应的列:#pragma db column("CatalogName")
4)指定数据库的主键自增长: #pragma db id auto
在用odb产生数据库支持代码时,有时候persistent类中引用了别的库, 在编译时可以通过-I添加路径。
比如:


posted @ 2013-07-05 09:27  muzizongheng  阅读(892)  评论(0编辑  收藏  举报
如果我们时时忙着展现自己的知识, 将何从忆起成长所需的无知?