person.h
#pragma once
#include <string>
#include <odb/core.hxx>
#include <odb/tr1/memory.hxx>
using namespace std;
using std::tr1::shared_ptr;
#pragma db object
class Person {
public:
Person() {}
Person(string a, string b) :
name(a), pass(b)
{
}
#pragma db id auto
unsigned long id;
string name;
string pass;
};
main.cpp
#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("account", "password", "databasename", "database_url", 3306));
//(insert).
{
Person john ("John", "Doe");
Person jane ("Jane", "Doe");
Person joe ("Joe", "Dirt");
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 ();
}
typedef odb::query<Person> query;
typedef odb::result<Person> result;
//(query).
{
transaction t(db->begin());
result r(db->query<Person>(query::name == "asd"));
for (auto i : r)
{
cout << "Hello, " << i.pass << "!" << endl;
}
t.commit();
}
//(update).
{
transaction t(db->begin());
result r(db->query<Person>(query::name == "asd"));
for (auto i : r)
{
cout << "Hello, " << i.pass << "!" << endl;
//i.pass = "test";
i.pass = "update";
db->update(i);
}
t.commit();
transaction upp(db->begin());
auto up(db->query_one<Person>(query::pass == "update"));
up->name = "update";
db->update(up);
upp.commit();
}
//(delete).
{
transaction t(db->begin());
// Here we know that there can be only one John Doe in our
// database so we use the query_one() shortcut again.
//
auto del(
db->query_one<Person>(query::name == "update" &&
query::pass == "update"));
db->erase(del);
t.commit();
}
}
catch (const odb::exception& e)
{
cerr << e.what() << endl;
return 1;
}
cin.get();
}