Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of a prepared INSERT statement using ruby pg gem

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>'
like image 892
iphone007 Avatar asked May 31 '12 21:05

iphone007


1 Answers

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.

like image 163
mu is too short Avatar answered Nov 13 '22 11:11

mu is too short