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( "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() ); } } }
- Run it and see the output in the Eclipse Console. If everything works fine the output should be like:
- 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!
jdbc:h2:tcp://localhost/~/test
should be used for Server Mode.
Thanks it works
thanks for a clear and simple tutorial. in your Start class on line 18 you have the
statement: stmt.executeUpdate( “DROP TABLE table1” );
This produced an error on my machine as it is executed before table1 is created
on line 19.
I ended up commenting out line 18 and got the results you described.
Thank you very much for your feedback. I updated the initial post and commented the line 18. This line was added to make the code rerunnable during test. It might be more obvious this way.
Great tutorial and simple for beginners.