使用PostgreSQL使用ActiveRecord准备和执行语句 [英] Prepare and execute statements with ActiveRecord using PostgreSQL
问题描述
我正在尝试使用ActiveRecord通过准备好的语句插入值。但是,每次我尝试:
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>
我该怎么办?我正在运行Rails 3.2.1和Ruby 1.9.2
What should I do? I'm running Rails 3.2.1 and Ruby 1.9.2
更新:
我解决了这个问题。感谢您的答复,但不适用于PostgreSQL。这样做的方法是:
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" } ]
其中,值是哈希数组,每个哈希指定一个值,$ 1绑定到第0个哈希,$ 2绑定到数组中的第2个哈希,依此类推
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!
推荐答案
从已编辑的问题正文中复制答案,以便从未答复过滤器中删除此问题:
Copying the answer from the edited question body, in order to remove this question from the "Unanswered" filter:
我解决了这个问题。感谢您的回应,但不适用于
PostgreSQL。这样做的方法是:
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" } ]
其中,值是一个哈希数组,每个哈希指定一个值,$ 1是
绑定到第0个哈希,$ 2绑定到数组中的第2个哈希,因此
on
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!
〜每个 alalani
这篇关于使用PostgreSQL使用ActiveRecord准备和执行语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!