Database Example

Throughout this book we will build a couple of applications that load and retrieve inventory data from DB databases. While we are not yet ready to begin reading from or writing to our databases, we can at least create the class that we will use to manage our databases.

Note that subsequent examples in this book will build on this code to perform the more interesting work of writing to and reading from the databases.

Note that you can find the complete implementation of these functions in:


where DB_INSTALL is the location where you placed your DB distribution.

Example 7.1 MyDbs Class

To manage our database open and close activities, we encapsulate them in the MyDbs class. There are several good reasons to do this, the most important being that we can ensure our databases are closed by putting that activity in the MyDbs class destructor.

To begin, we import some needed classes:

// File:
package db.GettingStarted;

import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.DatabaseType;


And then we write our class declaration and provided some necessary private data members:

public class MyDbs {

    // The databases that our application uses
    private Database vendorDb = null;
    private Database inventoryDb = null;

    private String vendordb = "VendorDB.db";
    private String inventorydb = "InventoryDB.db";

    // Our constructor does nothing
    public MyDbs() {} 

Next we need a setup() method. This is where we configure and open our databases.

    // The setup() method opens all our databases
    // for us.
    public void setup(String databasesHome)
        throws DatabaseException {

        DatabaseConfig myDbConfig = new DatabaseConfig();


        // Now open, or create and open, our databases
        // Open the vendors and inventory databases
        try {
            vendordb = databasesHome + "/" + vendordb;
            vendorDb = new Database(vendordb,

            inventorydb = databasesHome + "/" + inventorydb;
            inventoryDb = new Database(inventorydb,
        } catch(FileNotFoundException fnfe) {
            System.err.println("MyDbs: " + fnfe.toString());

Finally, we provide some getter methods, and our close() method.

   // getter methods
    public Database getVendorDB() {
        return vendorDb;

    public Database getInventoryDB() {
        return inventoryDb;

    // Close the databases
    public void close() {
        try {
            if (vendorDb != null) {

            if (inventoryDb != null) {
        } catch(DatabaseException dbe) {
            System.err.println("Error closing MyDbs: " +