C Question

Berkeley DB can't put then access data without closing db

I'm trying to use berkeley DB to store and get simple key/data pairs but that doesn't work as I expected.
I create one function ( putdb() ) to put a key/data pair in the database and another ( getdb() ) to retrieve this pair.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <db.h>
DB *dbp;
void opendb(void)
{
int ret;
if ((ret = db_create(&dbp, NULL, 0)) != 0)
exit(EXIT_FAILURE);
if ((ret = dbp->open(dbp, NULL, "db.db", NULL,DB_BTREE, DB_CREATE, 0664)) != 0)
exit(EXIT_FAILURE);
}


void putdb(const char *key, const char *value)
{
DBT keyValue, dataValue;
memset(&keyValue, 0, sizeof(keyValue));
memset(&dataValue, 0, sizeof(dataValue));

keyValue.size = sizeof(key);
dataValue.size = sizeof(value);

keyValue.data = malloc(keyValue.size);
strcpy(keyValue.data,key);

dataValue.data = malloc(dataValue.size);
strcpy(dataValue.data,value);

if ((ret = dbp->put(dbp, NULL, &keyValue, &dataValue, 0)) == 0)
printf("db: %s: key stored.\n", (char *)keyValue.data);
else {
dbp->err(dbp, ret, "DB->put");
}
dbp->sync(dbp, 0);
}

void getdb(const char *key,const char *value)
{
DBT keyValue, dataValue;
memset(&keyValue, 0, sizeof(keyValue));
memset(&dataValue, 0, sizeof(dataValue));

keyValue.size = sizeof(key);
dataValue.size = sizeof(value);

keyValue.data = malloc(keyValue.size);
strcpy(keyValue.data,key);

dataValue.data = malloc(dataValue.size);
strcpy(dataValue.data,value);

if ((ret = dbp->get(dbp, NULL, &keyValue, &dataValue, 0)) == 0)
printf("db: %s: key retrieved: data was %s.\n",
(char *)keyValue.data, (char *)dataValue.data);
else {
dbp->err(dbp, ret, "DB->get");
}
}
void closedb(void)
{
dbp->close(dbp, 0);
//TODO : error code return check
}


and the main file :

int main()
{
opendb();
putdb("toto","titi");
getdb("toto","titi");
closedb();
}


and I get :

db: toto: key stored.
DB->get: BDB0073 DB_NOTFOUND: No matching key/data pair found


Can you explain why ?

Notice if I change my main function :

int main()
{
opendb();
putdb("toto","titi");
closedb();
opendb();
getdb("toto","titi");
closedb();
}


then it works ! :

db: toto: key stored.
db: toto: key retrieved: data was titi.

Answer

You have copied too much from the tutorial. They can use sizeof("a string") but you have to use strlen(key) in both putdb and getdb

keyValue.size = strlen(key);
dataValue.size = strlen(value);
Comments