2012-05-31 66 views
10

做了大约半天的搜索,并且找不到使用pg gem(postgresql ruby​​ gem)准备好的INSERT语句的任何示例。使用ruby编写的INSERT语句示例pg 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>' 
+0

你能后整个文件吗?这可能有帮助,因为它的语法错误 - 它可能已经开始更远 – Jwosty

+0

@Jwosty:'ERROR:...(PG :: Error)'表明错误来自'pg'而不是Ruby。 –

+0

哦,这是有道理的......看起来这是OP的语法错误。我没有意识到宝石正在抛出错误(我以前从未使用过这个);谢谢! – Jwosty

回答

27

pg宝石要你使用编号的占位符($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.' ]) 

fine manual有这样一段话:

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

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.

+1

谢谢!这就是诀窍!呃,我不知道我是怎么错过的! – iphone007

+0

什么时候在执行它之前准备好声明是值得的? –

+1

@Martin:如果你想用不同的值多次执行相同的语句。一些数据库接口需要使用明确的准备语句来使用占位符,但'pg' gem可让您使用占位符['exec'](http://rubydoc.info/gems/pg/PG/Connection#exec-instance_method) 。 –