我有这段代码:
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"
我不明白。我错过了一些东西......
最佳答案
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
。
关于ruby - 将数组插入 postgresql 映射准备语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414526/