Ruby DBI:如何在使用方法时添加执行参数 "in (?)"

Ruby DBI: How to add the execute arguments when use method "in (?)"

这是我使用 DBI 的示例代码:

begin
  dbh = DBI.connect("DBI:Mysql:Test:localhost", "testuser", "testpassword")

  sql = "select u.email, u.account_name, u.height, u.weight 
         from test_users 
         where id in (?)
         group by u.id
         order by u.id
         into outfile '/tmp/test.csv'
         fields terminated by ','
         enclosed by '\"'
         lines terminated by '\n'"

  sth = dbh.prepare(sql)
  sth.execute('1,2,3')
  sth.finish
rescue DBI::DatabaseError => e
  puts "An error occurred"
  puts "Error code:    #{e.err}"
  puts "Error message: #{e.errstr}"
ensure
  # disconnect from server
  dbh.disconnect if dbh
end

但是 sql 它给我的感觉是 "in" 方法的值不正确:

  select u.email, u.account_name, u.height, u.weight 
  from test_users 
  where id in ('1,2,3')
  group by u.id
  order by u.id
  into outfile '/tmp/test.csv'
  fields terminated by ','
  enclosed by '\"'
  lines terminated by '\n'"

我要点赞(注意修改后的结果是:"id in (1,2,3)"):

   select u.email, u.account_name, u.height, u.weight 
   from test_users 
   where id in (1,2,3)
   group by u.id
   order by u.id
   into outfile '/tmp/test.csv'
   fields terminated by ','
   enclosed by '\"'

这不是 IN 子句的工作方式,您需要具有与参数数量相同的 ?,在您的情况下,您应该具有:

sql = "select u.email, u.account_name, u.height, u.weight 
         from test_users 
         where id in (?,?,?)
         group by u.id
         order by u.id
         into outfile '/tmp/test.csv'
         fields terminated by ','
         enclosed by '\"'
         lines terminated by '\n'"

然后将每个值传递给查询。

更一般地说,您可以使用 mapjoin:

生成占位符
foo = 'foo'
bar_array = [1, 2, 3]
bar_placeholders = bar_array.map { '?' }.join(', ')
baz = 18
sql = <<-SQL
  SELECT * FROM t
  WHERE foo = ?
  AND bar IN (#{bar_placeholders})
  AND baz > ?
SQL
...
sth.execute(foo, *bar_array, baz)

这将自动生成适当数量的问号,并正确引用参数。