Opening databases within the environment

Once the environment has been created, database handles may be created and then opened within the environment. This is done by calling the db_create() function and specifying the appropriate environment as an argument.

File naming, database operations, and error handling will all be done as specified for the environment. For example, if the DB_INIT_LOCK or DB_INIT_CDB flags were specified when the environment was created or joined, database operations will automatically perform all necessary locking operations for the application.

The following is a simple example of opening two databases within a database environment:

  1. DB_ENV *dbenv;
  2. DB *dbp1, *dbp2;
  3. int ret;
  4. dbenv = NULL;
  5. dbp1 = dbp2 = NULL;
  6. /*
  7. * Create an environment and initialize it for additional error
  8. * reporting.
  9. */
  10. if ((ret = db_env_create(&dbenv, 0)) != 0) {
  11. fprintf(errfp, "%s: %s\n", progname, db_strerror(ret));
  12. return (ret);
  13. }
  14. dbenv->set_errfile(dbenv, errfp);
  15. dbenv->set_errpfx(dbenv, progname);
  16. /* Open an environment with just a memory pool. */
  17. if ((ret =
  18. dbenv->open(dbenv, home, DB_CREATE | DB_INIT_MPOOL, 0)) != 0) {
  19. dbenv->err(dbenv, ret, "environment open: %s", home);
  20. goto err;
  21. }
  22. /* Open database #1. */
  23. if ((ret = db_create(&dbp1, dbenv, 0)) != 0) {
  24. dbenv->err(dbenv, ret, "database create");
  25. goto err;
  26. }
  27. if ((ret = dbp1->open(dbp1,
  28. NULL, DATABASE1, NULL, DB_BTREE, DB_CREATE, 0664)) != 0) {
  29. dbenv->err(dbenv, ret, "DB->open: %s", DATABASE1);
  30. goto err;
  31. }
  32. /* Open database #2. */
  33. if ((ret = db_create(&dbp2, dbenv, 0)) != 0) {
  34. dbenv->err(dbenv, ret, "database create");
  35. goto err;
  36. }
  37. if ((ret = dbp2->open(dbp2,
  38. NULL, DATABASE2, NULL, DB_HASH, DB_CREATE, 0664)) != 0) {
  39. dbenv->err(dbenv, ret, "DB->open: %s", DATABASE2);
  40. goto err;
  41. }
  42. return (0);
  43. err: if (dbp2 != NULL)
  44. (void)dbp2->close(dbp2, 0);
  45. if (dbp1 != NULL)
  46. (void)dbp1->close(dbp1, 0);
  47. (void)dbenv->close(dbenv, 0);
  48. return (1);
  49. }