sample-bdb.txt (2020B)
1 /* sample-bdb.txt - BerkeleyDB toy/sample 2 * 3 * Do a line-by-line comparison of this and sample-mdb.txt 4 */ 5 /* 6 * Copyright 2012-2021 Howard Chu, Symas Corp. 7 * All rights reserved. 8 * 9 * Redistribution and use in source and binary forms, with or without 10 * modification, are permitted only as authorized by the OpenLDAP 11 * Public License. 12 * 13 * A copy of this license is available in the file LICENSE in the 14 * top-level directory of the distribution or, alternatively, at 15 * <http://www.OpenLDAP.org/license.html>. 16 */ 17 #include <stdio.h> 18 #include <string.h> 19 #include <db.h> 20 21 int main(int argc,char * argv[]) 22 { 23 int rc; 24 DB_ENV *env; 25 DB *dbi; 26 DBT key, data; 27 DB_TXN *txn; 28 DBC *cursor; 29 char sval[32], kval[32]; 30 31 /* Note: Most error checking omitted for simplicity */ 32 33 #define FLAGS (DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_INIT_MPOOL|DB_CREATE|DB_THREAD) 34 rc = db_env_create(&env, 0); 35 rc = env->open(env, "./testdb", FLAGS, 0664); 36 rc = db_create(&dbi, env, 0); 37 rc = env->txn_begin(env, NULL, &txn, 0); 38 rc = dbi->open(dbi, txn, "test.bdb", NULL, DB_BTREE, DB_CREATE, 0664); 39 40 memset(&key, 0, sizeof(DBT)); 41 memset(&data, 0, sizeof(DBT)); 42 key.size = sizeof(int); 43 key.data = sval; 44 data.size = sizeof(sval); 45 data.data = sval; 46 47 sprintf(sval, "%03x %d foo bar", 32, 3141592); 48 rc = dbi->put(dbi, txn, &key, &data, 0); 49 rc = txn->commit(txn, 0); 50 if (rc) { 51 fprintf(stderr, "txn->commit: (%d) %s\n", rc, db_strerror(rc)); 52 goto leave; 53 } 54 rc = env->txn_begin(env, NULL, &txn, 0); 55 rc = dbi->cursor(dbi, txn, &cursor, 0); 56 key.flags = DB_DBT_USERMEM; 57 key.data = kval; 58 key.ulen = sizeof(kval); 59 data.flags = DB_DBT_USERMEM; 60 data.data = sval; 61 data.ulen = sizeof(sval); 62 while ((rc = cursor->c_get(cursor, &key, &data, DB_NEXT)) == 0) { 63 printf("key: %p %.*s, data: %p %.*s\n", 64 key.data, (int) key.size, (char *) key.data, 65 data.data, (int) data.size, (char *) data.data); 66 } 67 rc = cursor->c_close(cursor); 68 rc = txn->abort(txn); 69 leave: 70 rc = dbi->close(dbi, 0); 71 rc = env->close(env, 0); 72 return rc; 73 }