5

我正在尝试使用 ActiveRecord 通过准备好的语句插入值。但是,每次我尝试:

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

在第二个语句之后,我得到:

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

我该怎么办?我正在运行 Rails 3.2.1 和 Ruby 1.9.2

更新:

我解决了这个问题。感谢您的回复,但它不适用于 PostgreSQL。这样做的方法是:

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

其中 values 是一个散列数组,每个指定一个值,$1 绑定到第 0 个散列,$2 绑定到数组中的第 2 个散列,依此类推

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

女士们,先生们,这很有效!

4

1 回答 1

4

从已编辑的问题正文中复制答案,以便从“未回答”过滤器中删除此问题:

我解决了这个问题。感谢您的回复,但它不适用于 PostgreSQL。这样做的方法是:

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

于 2013-10-09T04:47:53.763 回答