Berkeley DB无法在不关闭db的情况下放入访问数据

时间:2016-09-04 00:30:44

标签: c berkeley-db

我正在尝试使用berkeley DB来存储和获取简单的密钥/数据对,但这并不像我预期的那样工作。 我创建了一个函数(putdb())来将一个键/数据对放在数据库中,另一个函数(getdb())来检索这一对。

#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
}

和主文件:

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

我得到了:

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

你能解释一下原因吗?

请注意我是否更改了我的主要功能:

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

然后它的作品! :

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

1 个答案:

答案 0 :(得分:3)

您从教程中复制了太多内容。他们可以使用true,但您必须在sizeof("a string")strlen(key)

中使用putdb
getdb