Ruby - 在SQL执行中传递绑定变量

时间:2014-01-07 04:57:06

标签: ruby-on-rails ruby

我是Ruby的新手,我想尝试访问MySQL数据库:

require 'rubygems'
require "dbi"

class DBConnection
  attr_accessor :dbh
  #Connect to db 
  def connect?(driver_url,user,pass)
    begin
      @dbh = DBI.connect(driver_url, user,pass);
      return true
    rescue DBI::DatabaseError => e
        puts "Error message: #{e.errstr}"
        @dbh.rollback
        return false
    ensure
      @dbh.disconnect if !dbh
    end
  end

  def execute_customize(query,params)
    stm = @dbh.prepare(query)
    if( (params != nil) && !(params.empty?) )
       stm.execute(params)
    else
      stm.execute
    end
    header = false
    stm.fetch do |row|
      if (!header)
          puts("ID   Name")
          header = true
      end
       puts("#{row[0]}   #{row[1]}")
    end
  end
end

db = DBConnection.new
db.connect?("DBI:Mysql:test:localhost", "root", "123456")
db.execute_customize("SELECT * FROM test.employee WHERE name = ? OR name = ? ",*["John","Terry"])

但上面的内容会返回以下错误:

in `execute_customize': wrong number of arguments (3 for 2) (ArgumentError)

但是执行成功了:

dbh.execute_customize("SELECT * FROM test.employee WHERE name = ?",*["John"])

我做错了什么?

Demo data from employee table :
+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Terry |
|    3 | Vidal |
|    4 | CR7   |
|    5 | M10   |
|    6 | R10   |
|    7 | F4    |
+------+-------+

//更新:您的评论几乎告诉我在查询中使用IN,但是如果使用其他查询:

SELECT * FROM test.employee WHERE name = ? and id > ?

我还需要一种方法将单独的游侠传递到每个“?”字符

1 个答案:

答案 0 :(得分:3)

你传递的是三个参数,而不是两个。

splat运算符*扩展数组,因此将其元素视为单独的参数。

尝试

dbh.execute("SELECT * FROM test.employee WHERE name IN (?)", names)

其中names是以逗号分隔的字符串列表。

这应该可行,但您可能不需要使用execute

如果你正在使用Rails,你可以使用

Employee.where(name: ["John","Terry"])

和ActiveRecord会明白你的意思。

请参阅http://guides.rubyonrails.org/active_record_querying.html