Java Embedded H2 Tutorial

This tutorial includes JAVA code to simplify the creation and use of H2 embedded databases.

The example 'little main test' creates an embedded database  on c:/tmp, named 'h2db' using
username 'sa' and password 'sasa', in server mode. Then it connects to it, does nothing (little main test does nothing, make it grow bigger), disconnects and then frees the resources used by the database before ending its execution.

public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException
  {
   // Instance an embedded H2
    EmbeddedH2 h2db = new EmbeddedH2();

    //Optional: set SQL mode
    //h2db.setH2SQLMode("MYSQL");
   
    //Optional, open it as server on port:
    h2db.setPort(9876);
   
    h2db.init(
      new File("f:/tmp"),
      "h2db",
      "sa",
      "sasa");
    
    System.out.println("OK.");
    
    // Create a connection
    Connection con=h2db.getConnection("sa", "sasa");
    // Do whatever you want to do with your connection, it is yours.
    con.close();
    
    // Remember to dispose database resources when finished or you
    // may encounter that your database files are locked next time
    // you try to access them.
    h2db.dispose();
  }

One of the many advantages of embedded databases consist on 'being part' of the code of the project one is working on; making it easier to deploy it on new machines. This 'coupling' may result a disadvantage if the codebase begins to grow, so being able to resolve that coupling if necessary should be taken in mind.

H2 offers a powerful embeddable database solution that even allows an application to launch its database tier in server mode. Once running in that mode, managing the database from H2's graphical user interface is a valuable option.

H2 may be installed on the same system where the embedded database exists, in that case, the H2 Console opens a webpage which can be used to visually inspect the database during runtime.

 
Launching H2 Console using Windows Start Menu.


Please, notice the JDBC URL textfield, as its value will be indicated in the logs during initialization of the EmbeddedH2 instance whose code is provided below.




It is also possible to access the database at the same time from Netbeans:


The password should be the one that is being used in the code to access the database, "sasa" in the test run.

Obviously, H2's driver library (h2-1.4.192.jar), should be included into the project to make it run.

And here goes the code.
EmbeddedH2.java
Download it as a library by clicking on the following link:
EmbeddedH2.jar

Comments

Popular posts from this blog

Qt Signals and Slots, Connecting and Disconnecting

Vaadin 7: Detect Enter Key in a TextField

JAVA JPA WITH HIBERNATE AND H2 Tutorial