Friday, February 26, 2010

HSQLDB - Java In-Memory Database

I've started using HSQLDB because of its in-memory database capabilities. My app reads a file, builds a database and populates it with data. It then allows me to run SQL queries against the data very easily. HSQLDB has many other useful features (like persistence) which I have not tried (nor have the need for) yet.

It is really easy to get up and running with HSQLDB.

  • Download HSQLDB from here.
  • Add hsqldb.jar to your classpath.
  • Create a connection like this:
    Class.forName("org.hsqldb.jdbc.JDBCDriver");
    Connection conn = DriverManager.getConnection(
                         "jdbc:hsqldb:mem:mydb", "SA", "");
    
  • Create a table like this:
    String bookTableSQL = "create memory table MY_TABLE ("+
    " TITLE varchar(256) not null primary key,"+
    " AUTHOR varchar(256) not null"+
    ");"
    Statement st = conn.createStatement();
    st.execute(bookTableSQL);
    
  • You can then insert records into the table and query it just as you would with an ordinary database table.
HSQLDB also has Text Tables which allows you to treat CSV (or other delimited) files as SQL tables.

No comments:

Post a Comment