如何在JRuby中初始化SQLite3 JDBC驱动程序? [英] How to initialize the SQLite3 JDBC driver in JRuby?

查看:152
本文介绍了如何在JRuby中初始化SQLite3 JDBC驱动程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you access SQLite3 via JDBC without using active record?

推荐答案

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

Here's an example that works with JRuby 1.6.6 (in Ruby 1.8 compat mode) with jdbc-sqlite3 3.7.2.

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

这篇关于如何在JRuby中初始化SQLite3 JDBC驱动程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆