Sunday, September 2, 2007

JRuby and Embedded Derby: First Steps

Before tackling ActiveRecord-JDBC I thought I'd play around with the embedded version of Apache Derby with JRuby. This actually took me a lot longer that it should of, mostly because its been months since I've done anything with JRuby and years since I've touched JDBC. But here are the basic steps, which probably aren't that much difference from any other JDBC in JRuby:

require 'java'
include_class "java.sql.Connection"
include_class "java.sql.DriverManager"
include_class "java.sql.ResultSet"
include_class "java.sql.Statement"
driver = org.apache.derby.jdbc.EmbeddedDriver.new()
conn = DriverManager.getConnection("jdbc:derby:derbyDB;create=true")
conn.setAutoCommit(false)
s = conn.createStatement()

Some of the things that tripped me up, as I was trying to convert the simple Java example to JRuby:
  • The Class.forName(driver).newInstance() nonsense, I guess I've never run across this convention before but probably not surprising since I'm not a Java developer
  • org.apache.derby.impl.jdbc.EmbedSQLException: Derby system shutdown - yes you should do a DriverManager.getConnection("jdbc:derby:;shutdown=true") and yes it apparently always throws an exception
  • Getting useful results sets back is where I spent most of my time. Fortunately Derby documentation (like most Apache projects) are among of the best of any, whether commercial or Open Source APIs.

Since Blogger mangles source code so badly, see the code over on my wiki. Next I'm going to try HSQLDB because it supports a larger set of rails migrations using ActiveRecord-JDBC than Derby, but the Hypersonic gem definitely had problems on OSX due to issues with YAJB. But me sneaking suspicions is that that library is for C-Ruby and not JRuby. Doh!

1 comment:

Arun Gupta said...

A similar set of instructions are also posted at: http://blogs.sun.com/arungupta/entry/totd_3_using_javadb_with