将数组插入postgresql map准备语句中

时间:2017-01-01 09:32:12

标签: ruby postgresql

我有这段代码:

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"

我不明白。我错过了一些东西......

2 个答案:

答案 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