一点说明:如果类成员发生了增减,只需要重新编译类模板文件生成对应的SQL脚本。再用新脚本生成表即可。
单表更新主要用的是用db->update(type)来更新记录
这里分两种情况:
(1)通过db->load(key)主键key来更新一条记录,之后修改记录,再更新记录
(2)通过db->query_one(bool)查询条件查询一条记录,之后修改记录,再更新记录
(1)通过主键更新的代码如下:
// 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
{
//auto_ptr<database> db (new odb::mysql::database (argc, argv));
//连接数据库
auto_ptr<odb::database> db (
new odb::mysql::database (
"root" // database login name
,"123456" // database password
,"collect" // database name
,"localhost"
,13306
));
typedef odb::query<person> query;
typedef odb::result<person> result;
// Say hello to those over 30.
//
{
transaction t (db->begin ());
unsigned long joe_id = 3;
auto_ptr<person> joe (db->load<person>(joe_id));
joe->age(joe->age()+1);
db->update(*joe);
t.commit ();
}
}
catch (const odb::exception& e)
{
cerr << e.what () << endl;
return 1;
}
}
执行前:
执行后:
(2)通过查询单条记录更新的代码如下:
// 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
{
//auto_ptr<database> db (new odb::mysql::database (argc, argv));
//连接数据库
auto_ptr<odb::database> db (
new odb::mysql::database (
"root" // database login name
,"123456" // database password
,"collect" // database name
,"localhost"
,13306
));
typedef odb::query<person> query;
typedef odb::result<person> result;
// Say hello to those over 30.
//
{
transaction t (db->begin ());
auto_ptr<person> joe (db->query_one<person>(query::first == "Joe"
&& query::last == "Dirt"));
joe->age(joe->age()+1);
db->update(*joe);
t.commit ();
}
}
catch (const odb::exception& e)
{
cerr << e.what () << endl;
return 1;
}
}
执行结果:
原文链接:http://www.codesynthesis.com/products/odb/doc/manual.xhtml#2.6