我正在构建一个命令行应用程序,它需要连接各种 postgresql 数据库并在这些数据库中执行不同的查询作为准备语句。在具体的查询中,需要结合ActiveRecord的connection_raw
方法使用IN
子句。我的代码是这样的:
ActiveRecord::Base.connection_raw.prepare('read_publications', "UPDATE publications SET readed = TRUE WHERE id IN ($1);")
之后,我尝试执行此查询:
ActiveRecord::Base.connection_raw.exec_prepared('read_publications', [1,2,3,4])
问题是这不起作用。查询运行时出现以下错误:
no implicit conversion of Array into Integer
我做错了什么?是否存在一种方法可以将此数组转换为 IN
子句可以理解的值?
最佳答案
如果您使用的是原始连接,则不能像使用 ActiveRecords 那样传入数组。 ActiveRecord 为您做一些预处理。如果您需要原始 SQL,则每个数组元素都需要一个参数。
arr = [1,2,3,4]
i = 1
param = []
arr.each { param.push(i); i+=1; }
sql = "UPDATE publications SET readed = TRUE WHERE id IN ($"+param.join(',$')+");"
ActiveRecord::Base.connection_raw.prepare('read_publications', sql)
ActiveRecord::Base.connection_raw.exec_prepared('read_publications', arr)
但是,文档说数组参数必须采用特定格式:
https://deveiate.org/code/pg/PG/Connection.html#method-i-exec_prepared
params is an array of the optional bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form: {:value => String (value of bind parameter) :format => Fixnum (0 for text, 1 for binary) }
查看类似问题:Prepare and execute statements with ActiveRecord using PostgreSQL
关于sql - Ruby 数组作为普通 SQL 查询的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36657925/