JRuby + Sqlitejdbc : No suitable driver found for

2019-08-30 18:49发布

问题:

On a machine I have only a user account on, I want to dump the output of a job into an sqlite database instead of textfiles. To this end, I run jruby from the jarfile.

The approach usings gems (dbi, dbd/Jdbc, jdbc/sqlite3) from a local GEM_HOME did not work (No suitable driver found) and also produces deprecation messages from the gems ("include_class is deprecated. Use java_import.")

I turned to Zentus' sqlitejdbc-v056.jar and ran JRuby with Zentus' in the path:

java -cp .:sqlitejdbc-v056.jar -jar jruby-complete-1.7.0.preview1.jar test.rb

where test.rb in inspired by http://www.zentus.com/sqlitejdbc/ and How to initialize the SQLite3 JDBC driver in JRuby? :

require 'java'
require '/home/jens/jruby/sqlitejdbc-v056.jar'

org.sqlite.JDBC                 # load the driver so DriverManager detects it 
p clazz = Java::JavaClass.for_name("org.sqlite.JDBC")
java.sql.DriverManager.registerDriver( clazz )
#Java::OrgSqlite::JDBC          # alternate means of same

puts "enumerating..."
java.sql.DriverManager.getDrivers.each{ |e| puts e }

connection = java.sql.DriverManager.getConnection 'jdbc:sqlite:/home/jens/jruby/test.db'
begin
  statement = connection.createStatement
  ...
ensure
  connection.close
end

The output I get from this is:

class org.sqlite.JDBC
enumerating...
sun.jdbc.odbc.JdbcOdbcDriver@73415727
DriverManager.java:602:in `getConnection': java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/jens/jruby/test.db
from DriverManager.java:207:in `getConnection'
from NativeMethodAccessorImpl.java:-2:in `invoke0'
    ...

Curiously, the driver is listed by the DriverManager, but not deemed suitable for sqlite.

I'm looking forward to any suggestions.

回答1:

First of all you should use bundler to manage your gem dependencies. Bundler uses a Gemfile to list the gems you need (place it where your script is). And make sure that jruby is in your path.

In your case the Gemfile should contain:

source 'http://rubygems.org'

gem "activerecord-jdbcsqlite3-adapter", ">= 1.2"

Then execute:

bundle install --path vendor/bundle

Then modify your script like this:

require 'rubygems'
require "java"
require 'bundler/setup'
require 'jdbc/sqlite3'

Bundler.require
org.sqlite.JDBC                 # load the driver so DriverManager detects it 
p clazz = Java::JavaClass.for_name("org.sqlite.JDBC")
java.sql.DriverManager.registerDriver( clazz )

puts "enumerating..."
java.sql.DriverManager.getDrivers.each{ |e| puts e }

connection = java.sql.DriverManager.getConnection 'jdbc:sqlite:/home/jens/jruby/test.db'
begin
  statement = connection.createStatement
ensure
  connection.close
end


标签: sqlite jruby