ruby - 在ruby中使用数组查询数据库

标签 ruby sqlite

我试图在数组中找到所有具有值的行,这是我的代码

require 'sqlite3'
db = SQLite3::Database.new('test.sqlite')
res = db.query("SELECT w1.synsetid
                FROM words w1
                WHERE w1.wordid IN (?)", arr)

arr: 字符串数组

我得到了这个错误

SQLite3::RangeException: bind or column index out of range

有什么帮助吗?

最佳答案

query 的第二个参数是一个占位符值数组:

- (Object) query(sql, bind_vars = [], *args)

This is a convenience method for creating a statement, binding paramters to it, and calling execute:

query 方法不知道它应该特殊对待您的 arr 数组,它只看到一个占位符和多个值。

我认为您必须以这种艰难的方式来做到这一点:构建适当数量的占位符并将它们粘贴到 SQL 中。像这样:

placeholders = (['?'] * arr.length).join(',')
res = db.query("select ... where w1.wordid in (#{placeholders})", arr)

您确切地知道 placeholders 中的内容,因此您不必担心在像这样构建 SQL 时使用字符串插值和注入(inject)问题。

如果您已经在使用 Rails,那么您还可以使用 ActiveRecord 包装您的 SQLite 表,然后使用通常的 ActiveRecord 接口(interface):

words = Word.where(:wordid => arr)

关于ruby - 在ruby中使用数组查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17605253/

相关文章:

iphone - NSData返回Null问题

ruby-on-rails - 加载Rails固定装置时获取“没有命名为列”

ruby - gem安装编码错误

python - 合并多个具有重叠数据的 Excel 工作表

python - 使用 Python : Course registration data in JSON 处理数据库

python - 将 Json 数据保存到 Sqlite Python

ruby-on-rails - 接收电子邮件 POP3 并保存在数据库中

访问模块和类元素的 Ruby 风格

javascript - 在 Ruby 和 JavaScript 中复制计算的最佳方法是什么?

ruby - 如何对 Resque 执行方法或 Resque Job 类进行基准测试?