c++ ODB操作测试

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();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值