ruby - 使用 PG gem 在参数化语句中进行多次插入

标签 ruby postgresql pg

使用 Ruby PG gem,我尝试使用 exec_params 同时插入多行。

我想实现的是:

INSERT INTO public.my_things (col1, col2)
VALUES
    ('value11', 'value12'),
    ('value21', 'value22'),
    ('value31', 'value32');

我试过这个(和其他组合):

connection.exec_params(
  'INSERT INTO public.my_things (col1, col2) VALUES ($1, $2)',
  [['value11', 'value12'], ['value21', 'value22'], ['value31', 'value32']],
)

最佳答案

有两点需要注意:

  1. 您需要适当数量的占位符。
  2. #exec_params 想要参数的平面数组。

所以你想说:

connection.exec_params(
  'INSERT INTO public.my_things (col1, col2) VALUES ($1, $2), ($3, $4), ($5, $6)',
  ['value11', 'value12', 'value21', 'value22', 'value31', 'value32']
)

或者,如果您有一个数组的数组,并且您不知道它在运行时需要多长时间:

aoa = [['value11', 'value12'], ['value21', 'value22'], ['value31', 'value32'], ... ]
values = aoa.length.times.map { |i| "($#{2*i+1}, $#{2*i+2})" }.join(',')
connection.exec_params(
  "INSERT INTO public.my_things (col1, col2) VALUES #{values}",
  aoa.flatten
)

关于ruby - 使用 PG gem 在参数化语句中进行多次插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488876/

相关文章:

ruby-on-rails - RMagick/ImageMagick 错误 "no decode delegate for this image format"与 Ruby Tempfile

ruby - 我如何让 intellij 选择代码完成建议而无需导航到它?

ruby - 使用 rvm 在 Mac OS Lion 上安装 pg gem

node.js - PG(node-postgres)VS。 Sequelize

database - PG::ConnectionBad: 运行后无法转换主机名错误 export DATABASE_URL=postgres://$(whoami)

ruby - #<Hash> 的未定义方法 `bytesize'

Ruby 类设置/获取

postgresql - Docker Postgresql远程访问

postgresql - 尝试理解 MVCC

Postgresql 启动失败