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;

5. dbenv = NULL;
6. dbp1 = dbp2 = NULL;
7. /*
8. * Create an environment and initialize it for additional error
9. * reporting.
10. */
11. if ((ret = db_env_create(&dbenv, 0)) != 0) {
12. fprintf(errfp, "%s: %s\n", progname, db_strerror(ret));
13. return (ret);
14. }

16. dbenv->set_errfile(dbenv, errfp);
17. dbenv->set_errpfx(dbenv, progname);

19. /* Open an environment with just a memory pool. */
20. if ((ret =
21. dbenv->open(dbenv, home, DB_CREATE | DB_INIT_MPOOL, 0)) != 0) {
22. dbenv->err(dbenv, ret, "environment open: %s", home);
23. goto err;
24. }

26. /* Open database #1. */
27. if ((ret = db_create(&dbp1, dbenv, 0)) != 0) {
28. dbenv->err(dbenv, ret, "database create");
29. goto err;
30. }
31. if ((ret = dbp1->open(dbp1,
32. NULL, DATABASE1, NULL, DB_BTREE, DB_CREATE, 0664)) != 0) {
33. dbenv->err(dbenv, ret, "DB->open: %s", DATABASE1);
34. goto err;
35. }

37. /* Open database #2. */
38. if ((ret = db_create(&dbp2, dbenv, 0)) != 0) {
39. dbenv->err(dbenv, ret, "database create");
40. goto err;
41. }
42. if ((ret = dbp2->open(dbp2,
43. NULL, DATABASE2, NULL, DB_HASH, DB_CREATE, 0664)) != 0) {
44. dbenv->err(dbenv, ret, "DB->open: %s", DATABASE2);
45. goto err;
46. }

48. return (0);

50. err:    if (dbp2 != NULL)
51. (void)dbp2->close(dbp2, 0);
52. if (dbp1 != NULL)
53. (void)dbp1->close(dbp1, 0);
54. (void)dbenv->close(dbenv, 0);
55. return (1);
56. }