CREATE TABLE students(student_id CHAR(4) NOT NULL,lastname CHAR(15),
firstname CHAR(15), PRIMARY KEY(student_id)); CREATE INDEX lname ON students(lastname);
struct student_record { char student_id[4]; char last_name[15]; char first_name[15];};void second(){ DB *dbp, *sdbp; int ret; /* 建立/開啟第一個資料庫*/ if ((ret = db_create(&dbp, dbenv, 0)) != 0) handle_error(ret); if ((ret = dbp->open(dbp, NULL, "students.db", NULL, DB_BTREE, DB_CREATE, 0600)) != 0) handle_error(ret); /* 開啟第二個資料庫,注意,需要申明這個庫支援重複記錄,因為學生的last_name不是唯一的,是可能重複的*/ if ((ret = db_create(&sdbp, dbenv, 0)) != 0) handle_error(ret); if ((ret = sdbp->set_flags(sdbp, DB_DUP | DB_DUPSORT)) != 0) handle_error(ret); if ((ret = sdbp->open(sdbp, NULL, "lastname.db", NULL, DB_BTREE, DB_CREATE, 0600)) != 0) handle_error(ret); /* 將二級個庫關聯到第一個庫上. 註:getname是提取key函數*/ if ((ret = dbp->associate(dbp, NULL, sdbp, getname, 0)) != 0) handle_error(ret);}/** getname -- 從第一個庫的鍵值對中提取第二個庫的key(即 last name)*/int getname(DB *secondary, const DBT *pkey, const DBT *pdata, DBT *skey){ /* * 這裡第二個key是資料的簡單結構,所以並不需要做其它的工作,直接返回就完事。 * 如果第二個key是需要從複雜記錄中提取出來再組建,這個使用者函數可能需要做分配空間和copy資料的工作;在這種情況下,對於第二個鍵的DBT結構需要設定 DB_DBT_APPMALLOC 標誌位;*/ memset(skey, 0, sizeof(DBT)); skey->data = ((struct student_record *)pdata->data)->last_name; skey->size = sizeof(((struct student_record *)pdata->data)->last_name); return (0);}
插入資料
struct student_record s;DBT data, key;memset(&key, 0, sizeof(DBT));memset(&data, 0, sizeof(DBT));memset(&s, 0, sizeof(struct student_record));key.data = "WC42";key.size = 4;memcpy(&s.student_id, "WC42", sizeof(s.student_id));memcpy(&s.last_name, "Churchill ", sizeof(s.last_name));memcpy(&s.first_name, "Winston ", sizeof(s.first_name));data.data = &s;data.size = sizeof(s);if ((ret = dbp->put(dbp, txn, &key, &data, 0)) != 0) handle_error(ret);
刪除資料
BT key;memset(&key, 0, sizeof(DBT));key.data = "WC42";key.size = 4;if ((ret = dbp->del(dbp, txn, &key, 0)) != 0) handle_error(ret);
DBT skey;memset(&skey, 0, sizeof(DBT));skey.data = "Churchill ";skey.size = 15;if ((ret = sdbp->del(sdbp, txn, &skey, 0)) != 0) handle_error(ret);
查詢資料
#include <db_cxx.h>int Db::get(DbTxn *txnid, Dbt *key, Dbt *data, u_int32_t flags);int Db::pget(DbTxn *txnid, Dbt *key, Dbt *pkey, Dbt *data, u_int32_t flags); pkey即第一索引的key;eg:DBT data, pkey, skey;memset(&skey, 0, sizeof(DBT));memset(&pkey, 0, sizeof(DBT));memset(&data, 0, sizeof(DBT));skey.data = "Churchill ";skey.size = 15;if ((ret = sdbp->pget(sdbp, txn, &skey, &pkey, &data, 0)) != 0) handle_error(ret);
錯誤處理
總結
更多參考