使用ruby pg gem准备的INSERT语句的示例 [英] Example of a prepared INSERT statement using ruby pg gem
问题描述
做了一些谷歌搜索大约半天,我找不到使用pg gem(PostgreSQL红宝石gem)准备的INSERT语句的任何样本。
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).
I尝试过此操作(在查看了gem文档之后):
I tried this (after looking at the gem docs):
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>'
推荐答案
pg
宝石希望您使用编号的占位符( $ 1
, $ 2
?):
The pg
gem wants you to use numbered placeholders ($1
, $2
, ...) rather than positional placeholders (?
):
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等。
- (PGresult) prepare(stmt_name, sql[, param_types ])
[...]
PostgreSQL bind parameters are represented as $1, $1, $2, etc., inside the SQL query.
再次针对 exec_prepared
:
PostgreSQL绑定参数在SQL查询中表示为$ 1,$ 1,$ 2等。 params数组的第0个元素绑定到$ 1,第一个元素绑定到$ 2,依此类推。
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.
这篇关于使用ruby pg gem准备的INSERT语句的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!