Example of a prepared INSERT statement using ruby pg gem

半腔热情 提交于 2019-12-03 12:10:54

问题


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

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

回答1:


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.' ])

The fine manual has this to say:

- (PGresult) prepare(stmt_name, sql[, param_types ])
[...]
PostgreSQL bind parameters are represented as $1, $1, $2, etc., inside the SQL query.

And again for 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.



来源:https://stackoverflow.com/questions/10841390/example-of-a-prepared-insert-statement-using-ruby-pg-gem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!