参考链接:
http://docs.oracle.com/cd/E17076_02/html/api_reference/C/dbcput.html
https://cn.forums.oracle.com/forums/thread.jspa?threadID=963421
电子书《BerkeleyDB-Core-Cxx-GSG.pdf》p72页对这两个flag进行描述
DB_AFTER
The data provided on the call to Dbc::put()is placed into the database as a duplicate record. The key used for this operation is the key used for the record to
which the cursor currently refers. Any key provided on the call to Dbc::put()is therefore ignored.
The duplicate record is inserted into the database immediately after the cursor's current position in the database.
This flag is ignored if sorted duplicates are supported for the database.
该段描述说明了,当打开cursor并引用记录之后,可以使用DB_AFTER将和当前cursor重复的记录插入到光标之后的位置(相对的,DB_BEFORE标识是插入cursor之前的位置)
备注:
在没有调用Dbc::get()将cursor引用记录的情况下,使用DB_AFTER或者DB_BEFORE将会报错,如下:
db exception: Dbc::put: Invalid argument
Press any key to continue
示例代码:
//支持不排序重复记录, 使用光标插入数据DB_AFTER
#include <iostream>
#include "db_cxx.h"
#define DATABASE "cursor_use.db"
struct MyData
{
int i;
char c;
int i1;
};
#define PUT_RECORDS_WITH_LEN(keystr, keylen, datastr, datalen, cursorp, flag) \
do { \
Dbt key(keystr, keylen); \
Dbt data(datastr, datalen); \
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 = NULL;
int nRet = 0;
try {
// set database flags
my_database.set_flags(DB_DUP); //此处要设置数据库支持不排序的重复记录
// open database
my_database.open(NULL, DATABASE, NULL, DB_BTREE, DB_CREATE, 0664);
// open cursor
my_database.cursor(NULL, &cursorp, 0);
int dataLen = 0;
dataLen = sizeof(MyData);
Dbt key("Alabama", strlen("Alabama") + 1);
Dbt data;
//获取"Alabama"所指的cursor, 然后使用DB_AFTER插入重复纪录
nRet = cursorp->get(&key, &data, DB_SET);
MyData data;
data.c = 'c';
data.i = 2;
data.i1 = 6;
PUT_RECORDS_WITH_LEN("Alabama", strlen("Alabama") + 1,
&data, dataLen, cursorp, DB_AFTER);
}
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;
}