我开始使用BerkeleyDB。我编写了以下方法将值插入数据库:
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; }
调用 Put() 方法,我没有错误。使用工具转储数据库 dump_db berkeley.db 获取数据库。它已经创建,但数据库中仍然没有值。
Put()
dump_db berkeley.db
知道吗?
如果您在退出程序之前没有关闭数据库,您可能希望这样做,例如,在您的 Put() 功能:
if(dbp->close(dbp, 0)) != 0) { printf("Close failed\n"); }
可能是您放入数据库的数据仅添加到缓存中,而未写入磁盘。在这种情况下,函数 close() 需要调用才能将数据刷新到磁盘:
close()
描述 这个 DB->close 函数将所有缓存的数据库信息刷新到磁盘,关闭所有打开的游标,释放所有分配的资源,并关闭所有底层文件。因为密钥/数据对缓存在内存中,所以无法将文件与 数据库->关 或 DB->sync 功能可能导致信息不一致或丢失。
这个 DB->close 函数将所有缓存的数据库信息刷新到磁盘,关闭所有打开的游标,释放所有分配的资源,并关闭所有底层文件。因为密钥/数据对缓存在内存中,所以无法将文件与 数据库->关 或 DB->sync 功能可能导致信息不一致或丢失。
DB->close
数据库->关
DB->sync