postgresql 使用 ruby pg gem 准备的 INSERT 语句示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10841390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Example of a prepared INSERT statement using ruby pg gem
提问by iphone007
Did some googling for about half a day and I can't find any sample of a prepared INSERT statement using the pg gem (postgresql ruby gem).
做了大约半天的谷歌搜索,我找不到任何使用 pg gem(postgresql ruby gem)准备好的 INSERT 语句的示例。
I tried this (after looking at the gem docs):
我试过这个(在查看了 gem 文档之后):
def test2
conn = PG.connect( dbname: 'db1' )
conn.prepare("statement1", 'INSERT INTO table1 (id, name, profile) VALUES (?, ?, ?)')
end
But I get the following error:
但我收到以下错误:
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>'
回答by mu is too short
The pg
gem wants you to use numbered placeholders ($1
, $2
, ...) rather than positional placeholders (?
):
该pg
宝石要你使用编号的占位符($1
,$2
,...),而不是位置的占位符(?
):
conn = PG.connect(:dbname => 'db1')
conn.prepare('statement1', 'insert into table1 (id, name, profile) values (, , )')
conn.exec_prepared('statement1', [ 11, 'J.R. "Bob" Dobbs', 'Too much is always better than not enough.' ])
The fine manualhas this to say:
该精细的手工有这样一段话:
- (PGresult) prepare(stmt_name, sql[, param_types ])
[...]
PostgreSQL bind parameters are represented as $1, $1, $2, etc., inside the SQL query.
- (PGresult) prepare(stmt_name, sql[, param_types ])
[...]
PostgreSQL 绑定参数在 SQL 查询中表示为 $1、$1、$2 等。
And again for exec_prepared
:
再次为exec_prepared
:
PostgreSQL bind parameters are represented as $1, $1, $2, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc.
PostgreSQL 绑定参数在 SQL 查询中表示为 $1、$1、$2 等。params 数组的第 0 个元素绑定到 $1,第一个元素绑定到 $2,依此类推。