在Ruby中,如何将变量传递到准备好的语句中?
我在Ruby中有一个查询数据库并打印出一些数据的方法,我尝试使用一个预先准备好的语句 以下是没有准备好的语句的函数方法:在Ruby中,如何将变量传递到准备好的语句中?,ruby,sqlite,prepared-statement,Ruby,Sqlite,Prepared Statement,我在Ruby中有一个查询数据库并打印出一些数据的方法,我尝试使用一个预先准备好的语句 以下是没有准备好的语句的函数方法: def print_state_speakers(*states) puts "STATE SPEAKERS" state_string = "'#{states.*"', '"}'" state_speakers = $db.execute(" SELECT name, location FROM congress_members W
def print_state_speakers(*states)
puts "STATE SPEAKERS"
state_string = "'#{states.*"', '"}'"
state_speakers = $db.execute("
SELECT name, location
FROM congress_members
WHERE location IN (#{state_string})
ORDER BY location")
state_speakers.each { |rep, location| puts "#{rep} - #{location}" }
end
def print_state_speakers(*states)
puts "STATE SPEAKERS"
state_string = "'#{states.*"', '"}'"
begin
pst = $db.prepare "SELECT name, location
FROM congress_members
WHERE location IN (?)
ORDER BY location"
state_speakers = pst.execute state_string
end
state_speakers.each { |rep, location| puts "#{rep} - #{location}" }
end
下面是我使用准备好的语句尝试相同的方法:
def print_state_speakers(*states)
puts "STATE SPEAKERS"
state_string = "'#{states.*"', '"}'"
state_speakers = $db.execute("
SELECT name, location
FROM congress_members
WHERE location IN (#{state_string})
ORDER BY location")
state_speakers.each { |rep, location| puts "#{rep} - #{location}" }
end
def print_state_speakers(*states)
puts "STATE SPEAKERS"
state_string = "'#{states.*"', '"}'"
begin
pst = $db.prepare "SELECT name, location
FROM congress_members
WHERE location IN (?)
ORDER BY location"
state_speakers = pst.execute state_string
end
state_speakers.each { |rep, location| puts "#{rep} - #{location}" }
end
下面是我调用该方法的地方:
print_state_speakers('NJ', 'NY' , 'ME', 'FL', 'AK')
当我使用第一种方法运行文件时,它显示数据,而当我使用第二种方法时,它什么也不显示。它不会抛出错误。我觉得要解释传入的字符串,语法需要有所不同,但我已经在网上搜索了一段时间,弄得一团糟,无法让它工作。如果您能了解如何修复准备好的声明,我们将不胜感激。如果您这样说:
pst = $db.prepare "SELECT name, location
FROM congress_members
WHERE location IN (?)
ORDER BY location"
state_speakers = pst.execute state_string
与任何其他字符串一样,pst.execute
调用将转义并引用state\u string
。但是您的状态字符串
实际上不是一个字符串,它是一个用(Ruby)字符串表示的SQL列表,因此您最终会对所有内容进行双引号引用
一个简单的解决方案是使用字符串插值添加适当数量的占位符,然后让SQLite3::Statement
处理所有引用本身:
placeholders = ([ '?' ] * states.length).join(',')
pst = $db.prepare "SELECT name, location
FROM congress_members
WHERE location IN (#{placeholders})
ORDER BY location"
state_speakers = pst.execute states
使用字符串插值是非常安全的,因为您确切地知道占位符中的内容非常有意义。非常感谢!