Special Offer: My C#/.NET Bootcamp Course is out now. Get 10% OFF using the code FRIENDS10.

An embedded database system is a database management system (DBMS) which is tightly integrated with an application software that requires access to stored data, such that the database system is “hidden” from the application’s end-user and requires little or no ongoing maintenance. (Source: Wikipedia.org)

In this post I am going to show you how you could implement an embedded database within a Java application.

  1. Download the Platform-Independent Zip.
  2. Extract it into your library folder on your local installation.
  3. Start Eclipse.
  4. Create a new project.
  5. Add the h2*.jar to the classpath of your new project.
  6. Setup a entry point of your application as you create a new class containing the following code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Start {
    
      /**
       * @param args
       */
      public static void main(String[] args)
      {
        try
        {
          Class.forName("org.h2.Driver");
              Connection con = DriverManager.getConnection("jdbc:h2:~/test", "test", "" );
              Statement stmt = con.createStatement();
              //stmt.executeUpdate( "DROP TABLE table1" );
              stmt.executeUpdate( "CREATE TABLE table1 ( user varchar(50) )" );
              stmt.executeUpdate( "INSERT INTO table1 ( user ) VALUES ( 'Claudio' )" );
              stmt.executeUpdate( "INSERT INTO table1 ( user ) VALUES ( 'Bernasconi' )" );
    
              ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
          while( rs.next() )
          {
              String name = rs.getString("user");
              System.out.println( name );
          }
          stmt.close();
          con.close();
        }
        catch( Exception e )
        {
          System.out.println( e.getMessage() );
        }
      }
    }

     

  7. Run it and see the output in the Eclipse Console. If everything works fine the output should be like:
  8. If you additionally want to create a *.jar file for sharing your project to another computer you have to take care that the lib h2*.jar is also exported. The exported jar file will be ca. 1-2 mb. See the following steps below:
  9. Right click on the projects home directory.
  10. Select Export.
  11. Select Runnable Jar file from the Java folder.
  12. Note: If you try to start the exported *.jar on another machine you won’t see any output. Therefore you have to check the home directory for new generated files. If there is a file called like that, everything worked!

Claudio Bernasconi

I'm an enthusiastic Software Engineer with a passion for teaching .NET development on YouTube, writing articles about my journey on my blog, and making people smile.