dbTalk Databases Forums  

Can't get C example to work

comp.databases.berkeley-db comp.databases.berkeley-db


Discuss Can't get C example to work in the comp.databases.berkeley-db forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Steve Kreisler
 
Posts: n/a

Default Can't get C example to work - 07-14-2005 , 10:08 AM






I'm trying to replicate the simple C examples in the Getting Started
documentation. When I run createDb, it creates a database, but when I
run readDb, it gives me "get failed: DB_NOTFOUND: No matching key/data
pair found". I'm running 4.1.24 on SunOS 5.8. Any help would be
appreciated.

createDb.c:
#include <stdio.h>
#include <string.h>
#include <db.h>

int main(int argc, char *argv[]) {
DBT key, data;
DB *dbp;
int ret;

float money = 122.45;
char *description = "Grocery bill.";

ret = db_create(&dbp, NULL, 0);

if (ret != 0)
fprintf(stderr, "db_create failed: %s\n", db_strerror(ret));

ret = dbp->open(dbp, NULL, "my_db.db",
NULL, DB_BTREE, DB_CREATE, 0);

if (ret != 0)
fprintf(stderr, "open failed: %s\n", db_strerror(ret));

memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));

key.data = &money;
key.size = sizeof(float);
data.data = description;
data.size = strlen(description) +1;

ret = dbp->put(dbp, NULL, &key, &data, DB_NOOVERWRITE);

if (ret != 0)
fprintf(stderr, "put failed: %s\n", db_strerror(ret));

if (dbp != NULL) dbp->close(dbp, 0);
}

readDb.c:
#include <stdio.h>
#include <string.h>
#include <db.h>

int main(int argc, char *argv[]) {
DBT key, data;
DB *dbp; /* DB structure handle */
int ret; /* function return value */

char *description;
float money = 122.45;

ret = db_create(&dbp, NULL, 0);

ret = dbp->open(dbp, NULL, "my_db.db",
NULL, DB_BTREE, DB_RDONLY, 0);
if (ret != 0)
fprintf(stderr, "open failed: %s\n", db_strerror(ret));

memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));

key.data = &money;
key.ulen = sizeof(float);
key.flags = DB_DBT_USERMEM;

ret = dbp->get(dbp, NULL, &key, &data, 0);
if (ret != 0)
fprintf(stderr, "get failed: %s\n", db_strerror(ret));

description = (char *)data.data;

printf("Money = %.2f Description = %s\n", money, description);

if (dbp != NULL) dbp->close(dbp, 0);
}


Reply With Quote
  #2  
Old   
Michael Cahill
 
Posts: n/a

Default Re: Can't get C example to work - 07-14-2005 , 08:24 PM






Hi Steve,

There's a bug in the Getting Started Guide -- the "get" code should set
up the key like this:

key.data = &money;
key.size = key.ulen = sizeof(float);
key.flags = DB_DBT_USERMEM;

Otherwise, it looks like a zero-length key to Berkeley DB.

Regards,
Michael.


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.