sample-bdb.txt 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. int main(int argc,char * argv[])
  21. {
  22. int rc;
  23. DB_ENV *env;
  24. DB *dbi;
  25. DBT key, data;
  26. DB_TXN *txn;
  27. DBC *cursor;
  28. char sval[32], kval[32];
  29. /* Note: Most error checking omitted for simplicity */
  30. #define FLAGS (DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_INIT_MPOOL|DB_CREATE|DB_THREAD)
  31. rc = db_env_create(&env, 0);
  32. rc = env->open(env, "./testdb", FLAGS, 0664);
  33. rc = db_create(&dbi, env, 0);
  34. rc = env->txn_begin(env, NULL, &txn, 0);
  35. rc = dbi->open(dbi, txn, "test.bdb", NULL, DB_BTREE, DB_CREATE, 0664);
  36. memset(&key, 0, sizeof(DBT));
  37. memset(&data, 0, sizeof(DBT));
  38. key.size = sizeof(int);
  39. key.data = sval;
  40. data.size = sizeof(sval);
  41. data.data = sval;
  42. sprintf(sval, "%03x %d foo bar", 32, 3141592);
  43. rc = dbi->put(dbi, txn, &key, &data, 0);
  44. rc = txn->commit(txn, 0);
  45. if (rc) {
  46. fprintf(stderr, "txn->commit: (%d) %s\n", rc, db_strerror(rc));
  47. goto leave;
  48. }
  49. rc = env->txn_begin(env, NULL, &txn, 0);
  50. rc = dbi->cursor(dbi, txn, &cursor, 0);
  51. key.flags = DB_DBT_USERMEM;
  52. key.data = kval;
  53. key.ulen = sizeof(kval);
  54. data.flags = DB_DBT_USERMEM;
  55. data.data = sval;
  56. data.ulen = sizeof(sval);
  57. while ((rc = cursor->c_get(cursor, &key, &data, DB_NEXT)) == 0) {
  58. printf("key: %p %.*s, data: %p %.*s\n",
  59. key.data, (int) key.size, (char *) key.data,
  60. data.data, (int) data.size, (char *) data.data);
  61. }
  62. rc = cursor->c_close(cursor);
  63. rc = txn->abort(txn);
  64. leave:
  65. rc = dbi->close(dbi, 0);
  66. rc = env->close(env, 0);
  67. return rc;
  68. }