开源中文网

您的位置: 首页 > 数据库应用 > Berkeley DB > 正文

C++的berkeleydb简单例子

来源:  作者:

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//only this head should include for use bdb.
#include "db_cxx.h"
#include "db.h"
int main()
{
//Creat and Open my_db.db
Db db(NULL, 0); // Instantiate the Db object
u_int32_t oFlags = DB_CREATE; // Open flags;
try {
// Open the database
db.open(NULL, // Transaction pointer
"my_db.db", // Database file name
  NULL, // Optional logical database name
  DB_BTREE, // Database access method
  oFlags, // Open flags
  0); // File mode (using defaults)
// DbException is not subclassed from std::exception, so
// need to catch both of these.
}
catch(DbException &e)
{
// Error handling code goes here
std::cerr << e.what() << std::endl;
}
catch(std::exception &e)
{
// Error handling code goes here
std::cerr << e.what() << std::endl;
}

//Put Data into my_db.db
char *description = "Grocery bill.";
float money = 122;
Dbt pkey(&money, sizeof(float));
Dbt pdata(description, strlen(description) + 1);
int ret = db.put(NULL, &pkey, &pdata, DB_NOOVERWRITE);
if (ret == DB_KEYEXIST)
{
db.err(ret, "Put failed because key %f already exists", money);
}
else
{printf("db: %s: data stored.\n", pdata.get_data());}
//Get Data from my_db.db

// Use our own memory to retrieve the float.
// For data alignment purposes.
//pkey.set_data(&money);
//pkey.set_ulen(sizeof(float));
//pkey.set_flags(DB_DBT_USERMEM);
db.get(NULL, &pkey, &pdata, 0);
printf("db: %s=%f: data get.\n", (char *)pdata.get_data(),money);
//Delet Data from my_db.db
db.del(NULL, &pkey, 0);
//Close my_db.db
try {
// Close the database
db.close(0);
// DbException is not subclassed from std::exception, so
// need to catch both of these.
}
catch(DbException &e) {
// Error handling code goes here
std::cerr << e.what() << std::endl;
}
catch(std::exception &e) {
// Error handling code goes here
std::cerr << e.what() << std::endl;
}
return(0);
}

Tags:C++ berkeleydb
关于开源中文网 - 联系我们 - 广告服务 - 网站地图 - 版权声明