坏主意。不要这样做,因为您正在使您的代码容易受到SQL注入攻击,并且还会让您的生活更加艰难。了解更多关于编写SQL语句,SQL注入等
总之,除非你使用的是一些ORM,你应该这样做:
#!/usr/bin/ruby
require 'pg'
if ARGV.length != 1 then
puts "Usage: prepared_statement.rb rowId"
exit
end
rowId = ARGV[0]
begin
con = PG.connect :dbname => 'testdb', :user => 'janbodnar'
con.prepare 'stm1', "SELECT * FROM Cars WHERE Id=$1"
rs = con.exec_prepared 'stm1', [rowId]
puts rs.values
rescue PG::Error => e
puts e.message
ensure
rs.clear if rs
con.close if con
end
(从一个拍摄http://zetcode.com/db/postgresqlruby/例如)
编辑:您不需要使用准备好的语句,也可以使用提供正确参数绑定的DB库方法:
require 'pg'
conn = PG::Connection.open(:dbname => 'test')
res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil])
查看文档for PG#exec_params
使用Ruby的Postgresql驱动程序传递参数。 –