Getting started with the H2 database

H2 database is a small and compact way to store data directly from Java, especially because it can use simple binary files as storage. My goal with these things is performance and large scale indexing of data. When speaking about large scale, I'm talking about hundreds of million rows.

On this blog post I'm adding some of the things that are useful for those interested in debugging this database.

Starting an interactive shell

java -cp h2.jar -url jdbc:h2:./ -user xyz -password 123456

Where you should adjust:
  • h2.jar is the library jar file from H2 (just a single file)
  • ./ is the filename for your database
  • "xyz" and "123456" are the user and password


Hello World (writing your first data and database to disk)

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)
            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( )
                String name = rs.getString("user");
                System.out.println( name );
        catch( Exception e )
            System.out.println( e.getMessage() );

This example was retrieved from Claudio Bernasconi (thank you!):

Relevant commands

To list your tables inside the database:

To list everything inside a table:

Where "MyTable" is naturally the name for your table.

Showing which INDEXES are associated with a table:
SELECT * FROM information_schema.indexes WHERE table_schema = 'PUBLIC' AND table_name='MyTable';

Relevant links related to performance

Several switches to improve performance:

Some people say that an active INDEX will slow down large scale data entry:!msg/h2-database/7U99fWMaMw0/FbpkXgWIrDcJ

Learn to add multiple data fields per SQL call to speed things up further:

No comments:

Post a Comment