I am starting to use BerkeleyDB. I wrote the following method to insert values to the database:
void Put(int key, int value){
DB *dbp;
int ret;
if((ret=db_create(&dbp,NULL,0))!=0){
fprintf(stderr,"db_create failed: %s\n",db_strerror(ret));
exit(1);
}
ret=dbp->open(
dbp,
NULL,
"berkeley.db",
NULL,
DB_BTREE,
DB_CREATE,
0
);
DBT bin_key, bin_value;
memset(&bin_key,0,sizeof(DBT));
memset(&bin_value,0,sizeof(DBT));
bin_key.data=&key;
bin_value.data=&value;
bin_key.size=sizeof(int);
bin_value.size=sizeof(int);
if((ret=dbp->put(dbp, NULL, &bin_key, &bin_value, DB_NOOVERWRITE))!=0){
printf("Put failed");
};
return;
}
After calling the Put()
method, I get no errors. Dumping the database with the tool dump_db berkeley.db
gets the database. It has been created, but still there are no values in the database.
Any idea?
In case you don't close your database before exiting your program, you might want to do that, for example, at the end of your Put()
function:
if(dbp->close(dbp, 0)) != 0)
{
printf("Close failed\n");
}
It might be that the data you put into your database is only added to the cache and not written to disk. In this case the function close()
needs to be called in order to flush your data to disk:
Description
The
DB->close
function flushes any cached database information to disk, closes any open cursors, frees any allocated resources, and closes any underlying files. Because key/data pairs are cached in memory, failing to sync the file with theDB->close
orDB->sync
function may result in inconsistent or lost information.