sql - Ruby 数组作为普通 SQL 查询的参数

标签 sql ruby-on-rails ruby postgresql

我正在构建一个命令行应用程序,它需要连接各种 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/

相关文章:

mysql - Rails 联合查询

html - 没有路由匹配缺少所需的键 : [:id]

ruby-on-rails - Geocoder 的手动模拟

c# - AES/GCM (AES-128-GCM) 身份验证标签在 C# 和 Ruby 中不同

Sql Server 系统进程查询

ruby-on-rails - 我如何在条件中执行更新语句

java - @formula 注释或 sql 解密函数的替代方案

ruby-on-rails - Rails + Postgres 丢弃错误 : database is being accessed by other users

mysql - 如何在 SQL 数据库中选择最新的 x 个条目

sql - 查询以查找一个表中的行总和等于另一个表中的一个或多个行