如何在JRuby中初始化SQLite3 JDBC驱动程序?

时间:2009-11-11 19:58:16

标签: java ruby sqlite jdbc jruby

如何在不使用活动记录的情况下通过JDBC访问SQLite3?

3 个答案:

答案 0 :(得分:5)

这是一个使用jubc-sqlite3 3.7.2的JRuby 1.6.6(在Ruby 1.8 compat模式下)的示例。

require 'rubygems'
require 'jdbc/sqlite3'
require 'java'

org.sqlite.JDBC                 # load the driver so DriverManager detects it 
#Java::OrgSqlite::JDBC          # alternate means of same

connection = java.sql.DriverManager.getConnection 'jdbc:sqlite:test.sqlite3'
begin
  statement = connection.createStatement
  begin
    statement.executeUpdate("create table user (name varchar, pass varchar)")
    statement.executeUpdate("insert into user values ('alice', 1234)")
    statement.executeUpdate("insert into user values ('bob', 5678)")
    statement.executeUpdate("insert into user values ('charlie', 'asdf')")

    rs = statement.executeQuery("select * from user")
    begin
      puts "user\tpass"
      while rs.next
        puts ["#{rs.getString(1)}",
              "#{rs.getString(2)}"].join("\t")
      end
    ensure
      rs.close
    end

  ensure
    statement.close
  end
ensure
  connection.close
end

输出:

$ rm -f test.sqlite3; ruby sql.rb
user    pass
------------
alice   1234
bob     5678
charlie asdf

答案 1 :(得分:1)

安装jdbc-sqlite3 gem

然后,在你的jruby脚本中:

require 'jdbc/sqlite3'
url = "jdbc:sqlite:path.to.your.db"
begin        
    Java::org.sqlite.JDBC #initialize the driver
    connection = JavaLang::DriverManager.getConnection(url) #grab your connection
rescue => error      
    #handle error
end

答案 2 :(得分:0)

jdbc驱动程序文件sqlite-3.5.8.jar被复制到gem目录中。它需要复制到jruby / lib目录中。应用程序也需要重新启动。

驱动程序文件可以直接从这里下载

http://files.zentus.com/sqlitejdbc/sqlitejdbc-v056.jar

http://www.zentus.com/sqlitejdbc/