0

我正在按照教程在 JRuby 中建立 ojdbc 连接,以便我可以执行一些 SQL 语句。但它无法连接到数据库。以下是步骤:

  1. 将 ojdbc6.jar 复制到 ruby​​ 文件所在的工作目录下。
  2. 创建 oracle_connection.rb 文件
  3. 创建 test_connection.rb 文件作为驱动类

oracle_connection.rb

require 'java'
require 'ojdbc6.jar'
java_import 'oracle.jdbc.OracleDriver'

 java_import 'java.sql.DriverManager'

class OracleConnection
@conn = nil
@user = nil
@pwd = nil

def initialize(user, pwd, url)
    @user = user
    @pwd = pwd
    @url = url


    #Load driver class
    ora_driver = OracleDriver.new

    DriverManager.registerDriver ora_driver
    @conn = DriverManager.get_connection url, user, pwd
    @conn.auto_commit = false
end

#Add getters and setters for all attributes we wish to expose
attr_reader :user, :pwd, :url, :connection

def close_connection()
    @conn.close() unless @conn
end

def prepare_call(call)
    @conn.prepare_call call
end

def create_statement()
    @conn.create_statement
end

def prepare_statement(sql)
    @conn.prepare_statement sql
end

def commit()
    @conn.commit
end

def to_s
    "OracleConnection [user=#{@user}, url=#{@url}]"
end
alias_method :to_string, :to_s
end


#test_connection.rb
require 'oracle_connection'

#Edit these for your database schema
user = "ABC"
pwd = "EFG"
url = "jdbc:oracle:thin:@host_name:1520/db_instance"

print "Run at #{Time.now} using JRuby #{RUBY_VERSION}\n\n"

begin
   conn = OracleConnection.new.create(user, pwd, url)

   puts conn, "\n"
end

print "\nEnded at #{Time.now}\n"

运行 test_connection.rb 时,我看到以下错误:

ruby test_connection.rb
Run at 2013-09-16 10:11:05 -0700 using JRuby 1.9.2
NoMethodError: undefined method `create' for OracleConnection:Class
(root) at test_connection.rb:11

我不知道是什么导致了问题。对此的指导非常感谢。谢谢!

4

1 回答 1

0

在“test_connection.rb”中,我调用了“create”方法,而在 OracleConnection 类中没有定义“create”方法。因此它失败了。

将conn = OracleConnection.new.create(user, pwd, url)替换为conn = OracleConnection.new(user, pwd, url)解决了这个问题。

下面我正在重写工作 test_connection.rb

#test_connection.rb
require 'oracle_connection'

#Edit these for your database schema
user = "ABC"
pwd = "EFG"
url = "jdbc:oracle:thin:@host_name:1520/db_instance"

print "Run at #{Time.now} using JRuby #{RUBY_VERSION}\n\n"

begin
   conn = OracleConnection.new(user, pwd, url)

   puts conn, "\n"
end

print "\nEnded at #{Time.now}\n"
于 2013-09-16T18:16:41.083 回答