I am Mr. Rourke...er...Bill Dueber, your host.

Using SQLite3 from JRuby without ActiveRecord



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:


  gem install dbi
  gem install dbd-jdbc
  gem install jdbc-sqlite3

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


require 'rubygems' # if you're using 1.8 still
require 'java'
require 'dbi'
require 'dbd/jdbc'
require 'jdbc/sqlite3'

databasefile = 'test.db'
dbh = DBI.connect(
  "DBI:jdbc:sqlite:#{databasefile}",  # connection string
  '',                                 # no username for sqlite3
  '',                                 # no password for sqlite3
  'driver' => 'org.sqlite.JDBC')      # need to set the driver

# That's it. Everything below here is stock DBI

dbh.do "create table squares (i integer, isquared integer)"

ins = dbh.prepare("insert into squares values (?, ?)")
(1..20).each do |i|
  ins.execute(i, i*i)
end




Commentaires

comments powered by Disqus