Home > Uncategorized > Using SQLite3 from JRuby without ActiveRecord

Using SQLite3 from JRuby without ActiveRecord

May 26, 2011 Comments Off

I spent way too long asking my friend, The Internet, how to get a normal DBI connection to SQLIte3 using JRuby. Apparently, everyone except me is using ActiveRecord and/or Rails and doesn’t want to just connect to the database.

But I do. Here’s how.

First, get the gems:

  1.   gem install dbi
  2.   gem install dbd-jdbc
  3.   gem install jdbc-sqlite3

Then you’re ready to load it up into DBI.

  1. require 'rubygems' # if you're using 1.8 still
  2. require 'java'
  3. require 'dbi'
  4. require 'dbd/jdbc'
  5. require 'jdbc/sqlite3'
  6.  
  7. databasefile = 'test.db'
  8. dbh = DBI.connect(
  9.   "DBI:jdbc:sqlite:#{databasefile}",  # connection string
  10.   '',                                 # no username for sqlite3
  11.   '',                                 # no password for sqlite3
  12.   'driver' => 'org.sqlite.JDBC')      # need to set the driver
  13.  
  14. # That's it. Everything below here is stock DBI
  15.  
  16. dbh.do "create table squares (i integer, isquared integer)"
  17.  
  18. ins = dbh.prepare("insert into squares values (?, ?)")
  19. (1..20).each do |i|
  20.   ins.execute(i, i*i)
  21. end

Tags:

Comments are closed.