Prepare and execute statements with ActiveRecord using PostgreSQL

佐手、 提交于 2020-01-03 13:04:04

问题


I am trying to insert values via a prepared statement using ActiveRecord. However, everytime I try:

conn = ActiveRecord::Base.connection
conn.prepare "SELECT * from sampletable where id = $1"
conn.execute 3

After the second statement, I get:

NoMethodError: undefined method `prepare' for
#<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter:0x000001027442c8>

What should I do? I'm running Rails 3.2.1 and Ruby 1.9.2

UPDATE:

I solved the problem. Thanks for the response, but it didn't work for PostgreSQL. The way to do it is:

stmt = "SELECT * from sampletable where id = $1 and name = $2"
values = [ { value: 1}, { value: "henry" } ]

where values is an array of hashes, each specifying a value, $1 is bound to the 0th hash, $2 is bound to the 2nd hash in the array and so on

con = PG::Connection.new(:dbname => "development_DB")
con.prepare("insert", stmt)
con.exec_prepared("insert", values)
con.close()

And this, ladies and gentlemen, works!


回答1:


Copying the answer from the edited question body, in order to remove this question from the "Unanswered" filter:

I solved the problem. Thanks for the response, but it didn't work for PostgreSQL. The way to do it is:

stmt = "SELECT * from sampletable where id = $1 and name = $2"
values = [ { value: 1}, { value: "henry" } ]

where values is an array of hashes, each specifying a value, $1 is bound to the 0th hash, $2 is bound to the 2nd hash in the array and so on

con = PG::Connection.new(:dbname => "development_DB")
con.prepare("insert", stmt)
con.exec_prepared("insert", values)
con.close()

And this, ladies and gentlemen, works!

~ answer per alalani



来源:https://stackoverflow.com/questions/13961005/prepare-and-execute-statements-with-activerecord-using-postgresql

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