简体   繁体   English

无法将DBI :: DatabaseHandle对象作为红宝石gem方法的参数传递

[英]Can not pass a DBI::DatabaseHandle object as an argument to a ruby gem method

I'm new to ruby so forgive me in advance if this is a silly question. 我是红宝石的新手,所以如果这是一个愚蠢的问题,请提前原谅我。 I've googled for answers but nothing relevant comes up and it seems the answer should be obvious. 我已经用谷歌搜索了答案,但是没有相关的东西出现,而且答案似乎很明显。

I'm attempting to pass a DBI::DatabaseHandle as function argument and I'm getting a wrong "number of arguments" error when I run the function. 我试图将DBI :: DatabaseHandle传递为函数参数,并且在运行函数时遇到错误的“参数数量”错误。 Here's my code... 这是我的代码...

require 'rubygems'
require 'dbi'

class CmsTest

    def self.get_dbi_connection(hostname, user, password)
        connection = DBI.connect("DBI:OCI8:" + hostname, user, password)
        return connection
    end

    def self.query(connection, sql)
        puts connection
        puts sql
        begin
            request = connection.prepare("#{query}")
            request.execute
            fetched = []
            request.fetch do |row|
                fetched << row.to_h 
            end 
            request.finish
            return fetched
        rescue DBI::DatabaseError => e
            log "An error occurred"
            log "Error code:    #{e.err}"
            log "Error message: #{e.errstr}"
        ensure
        end
    end
end

So my code that calls this looks like so... 所以我的代码调用它看起来像这样...

require 'rubygems'
require 'cms_test'

connection = CmsTest.get_dbi_connection('foo', 'bar', 'fubar')
CmsTest.query(connection, "<some sql query>")

So the first argument is a DBI::DatabaseHandle object and the second is some sql query string. 因此,第一个参数是一个DBI :: DatabaseHandle对象,第二个参数是一些sql查询字符串。 When I run that I get this... 当我跑步时,我得到了...

`query': wrong number of arguments (0 for 2) (ArgumentError)

This even though the query signature contains two arguments and and I'm passing the method two arguments. 即使查询签名包含两个参数,并且我正在向方法传递两个参数,也是如此。 The really weird thing for me is that if I put and exit statement anywhere in the method body after the puts it will show that the method did indeed receive 2 arguments... 对我来说,真正的怪异之处在于,如果在放置之后在方法主体中的任何位置放置和退出语句,它将表明该方法确实接收了两个参数...

#<DBI::DatabaseHandle:0x007fa2a316c9f0>
select licensor_id, licensor_name from cf_licensor

I can't make any sense of this. 我对此毫无意义。 Please help. 请帮忙。

You have a method named query : 您有一个名为query的方法:

def self.query(connection, sql)

and then inside query you try to call query : 然后在query内部尝试调用query

request = connection.prepare("#{query}")
# -- method call ---------------^^^^^

You probably want to use sql there and there's no need for string interpolation: 您可能想在那里使用sql ,并且不需要字符串插值:

request = connection.prepare(sql)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM