我有这段代码:
require 'pg'
a = ["bla","foo","bar","test","wow"]
begin
con = PG.connect :dbname => 'base', :user => 'thatsme'
a.map do |e|
con.prepare('statement1','INSERT INTO keywords (keyword, created_at, updated_at) VALUES ($1, $2, $3)')
con.exec_params('statement1', ["#{e}", '2017-01-01 07:29:33.096192', '2017-01-01 07:29:33.096192' ])
end
这会导致错误,即
ERROR: syntax error at or near "statement1"
我不明白。我错过了一些东西......
答案 0 :(得分:2)
exec_params
方法没有采用预先准备好的语句名称,这不是受支持的参数。
您可能打算使用具有该参数的send_query_prepared
方法。
这是您的代码的重构版本:
a.each_with_index do |r, i|
con.prepare("statement_#{i}","INSERT INTO keywords (keyword, created_at, updated_at) VALUES ($1, $2, $3)")
con.exec_prepared("statement_#{i}", [r, '2017-01-01 07:29:33.096192', '2017-01-01 07:29:33.096192' ])
end
如果您不关心结果,则应使用each
代替map
,因为map
会创建重写条目的临时数组。另外each_with_index
避免手动操作i
。
答案 1 :(得分:0)
这是解决方案(如果这可以帮助某人):
con = PG.connect :dbname => 'base', :user => 'thatsme'
i = 1;
a.map do |r|
con.prepare("statement_#{i}","INSERT INTO keywords (keyword, created_at, updated_at) VALUES ($1, $2, $3)")
con.exec_prepared("statement_#{i}", [r.to_s, '2017-01-01 07:29:33.096192', '2017-01-01 07:29:33.096192' ])
i += 1
end