写记录示例:
#include <iostream>
#include "db_cxx.h"
#define DATABASE "duplicated.db"
#define PUT_RECORDS(keystr, datastr, cursorp, flag) \
do { \
Dbt key(keystr, strlen(keystr) + 1); \
Dbt data(datastr, strlen(datastr) + 1); \
nRet = cursorp->put(&key, &data, flag); \
std::cout << keystr << " put result: " << nRet << std::endl; \
} while (0);
int main()
{
Db my_database(NULL, 0);
Dbc* cursorp;
int nRet = 0;
try {
// set database flags
my_database.set_flags(DB_DUPSORT); //此处要设置数据库支持排序的重复记录
// open database
my_database.open(NULL, DATABASE, NULL, DB_BTREE, DB_CREATE, 0664);
// open cursor
my_database.cursor(NULL, &cursorp, 0);
PUT_RECORDS("Alabama", "Athens", cursorp, DB_KEYFIRST);
PUT_RECORDS("Alabama", "Florence", cursorp, DB_KEYFIRST);
PUT_RECORDS("Alaska", "Anchorage", cursorp, DB_KEYFIRST);
PUT_RECORDS("Alaska", "Fairbanks", cursorp, DB_KEYFIRST);
PUT_RECORDS("Arizona", "Florence", cursorp, DB_KEYFIRST);
}
catch (DbException& e) {
std::cout << "db exception: " << e.what() << std::endl;
}
catch (std::exception &e) {
std::cout << "std::exception: " << e.what() << std::endl;
}
if (cursorp != NULL)
cursorp->close();
my_database.close(0);
return 0;
}
读取记录示例:
#include <iostream>
#include <db_cxx.h>
#include <string>
#define DATABASE "duplicated.db"
int main()
{
Db my_database(NULL, 0);
Dbc* cursorp = NULL;
int nRet = 0;
try {
// open database
my_database.open(NULL, DATABASE, NULL, DB_BTREE, DB_RDONLY, 0664);
// open cursor
my_database.cursor(NULL, &cursorp, 0);
Dbt key1, data1;
// print all records
while ((nRet = cursorp->get(&key1, &data1, DB_NEXT)) != DB_NOTFOUND) {
std::cout << (char*)key1.get_data() << " " << (char*)data1.get_data() << std::endl;
}
}
catch (DbException& e) {
std::cout << "db exception: " << e.what() << std::endl;
}
catch (std::exception &e) {
std::cout << "std::exception: " << e.what() << std::endl;
}
if (cursorp != NULL)
cursorp->close();
my_database.close(0);
}
输出结果:
Alabama Athens
Alabama Florence
Alaska Anchorage
Alaska Fairbanks
Arizona Florence
Press any key to continue