
H2: Embedded Java DB: Getting Started
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.
-
Download the Platform-Independent Zip.
-
Extract it into your library folder on your local installation.
-
Start Eclipse.
-
Create a new project.
-
Add the h2*.jar to the classpath of your new project.
-
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( "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() ); } } } -
Run it and check the output in the Eclipse Console.
-
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:
-
Right click on the projects home directory.
-
Select Export.
-
Select Runnable Jar file from the Java folder.
-
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!
