14

谷歌搜索了大约半天,我找不到任何使用 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

但我收到以下错误:

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>'
4

1 回答 1

34

pggem 希望您使用编号占位符 ( , $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.' ])

精美的手册是这样说的:

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

再次为exec_prepared

PostgreSQL 绑定参数在 SQL 查询中表示为 $1、$1、$2 等。params 数组的第 0 个元素绑定到 $1,第一个元素绑定到 $2,以此类推。

于 2012-05-31T21:24:26.173 回答