16 November 2011

JDBC, JRuby and Oracle

Connecting to Oracle from MRI Ruby is pretty easy, thanks to the excellent OCI8 drivers.

Sometimes it can be useful to use the very robust Oracle JDBC drivers and connect to Oracle over JDBC, which is possible using JRuby.

  • First install JRuby
    • Next get the Oracle JDBC drivers by downloading ojdbc6.jar from Oracle
    • Put the ojdbc6.jar file into the lib directory inside jruby install, eg C:\jruby-1.6.5\lib

With all that installed, the following code should connect successfully to Oracle:

require 'java'

java_import 'oracle.jdbc.OracleDriver'
java_import 'java.sql.DriverManager'

oradriver = OracleDriver.new
DriverManager.registerDriver oradriver
conn = DriverManager.get_connection('jdbc:oracle:thin:@localhost/local11gr2.world',
                           'user', 'password')
conn.auto_commit = false

stmt = conn.prepare_statement('select * from dual');

rowset = stmt.executeQuery()
while (rowset.next()) do
  puts rowset.getString(1)
end
blog comments powered by Disqus