Friday, June 17, 2011

How to setup H2 database for database connections in java?

Download H2 database
Download H2 database from - H2 download, I downloaded the platform independent version. Extract the zip to some directory.
Run the H2 engine
Now migrate to bin extracted folder, and go to bin folder. Double click on h2.bat and the database engine starts.
Add the jars 
Add H2 jar present in the same bin folder to the java project and add following class to the project and run it.

Now test the code:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class H2Test
{
  public static void main( String args[] ) throws Exception
  {
    Class.forName( "org.h2.Driver" );
    Connection conn = null;
    Statement stmt = null;

    try
    {
      conn = DriverManager.getConnection( "jdbc:h2:file:db/test", "sa", "" );
      stmt = conn.createStatement();
      stmt.executeUpdate( "create table person(name varchar(10));" );
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
    finally
    {
      if( stmt != null )
      {
        try
        {
          stmt.close();
          System.out.println("Test done");
        }
        catch( Exception e )
        {
          e.printStackTrace();
        }
      }

      if( conn != null )
      {
        conn.close();
      }

    }

  }
}


No comments:

Post a Comment

Chitika