使用ruby pg gem准备好的INSERT语句的示例

iph*_*007 11 ruby postgresql pg

有些谷歌搜索大约半天,我找不到使用pg gem(postgresql ruby​​ gem)准备的INSERT语句的任何样本.

我试过这个(看完gem文档后):

def test2
    conn = PG.connect( dbname: 'db1' )
    conn.prepare("statement1", 'INSERT INTO table1 (id, name, profile) VALUES (?, ?, ?)')
end
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

pgtest.rb:19:in `prepare': ERROR:  syntax error at or near "," (PG::Error)
LINE 1: INSERT INTO table1 (id, name, profile) VALUES (?, ?, ?)
                                                        ^
from pgtest.rb:19:in `test2'
from pgtest.rb:25:in `<main>'
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 33

pg宝石要你使用编号的占位符($1,$2,...),而不是位置的占位符(?):

conn = PG.connect(:dbname => 'db1')
conn.prepare('statement1', 'insert into table1 (id, name, profile) values ($1, $2, $3)')
conn.exec_prepared('statement1', [ 11, 'J.R. "Bob" Dobbs', 'Too much is always better than not enough.' ])
Run Code Online (Sandbox Code Playgroud)

精细的手工有这样一段话:

- (PGresult) prepare(stmt_name, sql[, param_types ])
[...]
PostgreSQL绑定参数在SQL查询中表示为$ 1,$ 1,$ 2等.

并再次exec_prepared:

PostgreSQL绑定参数在SQL查询中表示为$ 1,$ 1,$ 2等.params数组的第0个元素绑定到$ 1,第1个元素绑定到$ 2,等等.

  • @DavidAldridge是的,我使用的是不同的值.但是,我现在意识到延迟是因为它们是写入的.它掩盖了准备的延迟.当我阅读时,我得到了明显的改善. (2认同)