【二】ODB - C++ 單表插入(V1.02)

CalmReason發表於2015-11-02

插入資料主要有如下幾個步驟:
(1)建立資料庫連線物件
(2)建立本地物件
(3)插入資料到表
(4)統一提交


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

這裡寫圖片描述

原文地址:
http://www.codesynthesis.com/products/odb/doc/manual.xhtml#2.4

相關文章