gpt4 book ai didi

ruby-on-rails - 使用 PostgreSQL 使用 ActiveRecord 准备和执行语句

转载 作者:行者123 更新时间:2023-12-04 20:14:38 25 4
gpt4 key购买 nike

我正在尝试使用 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 绑定(bind)到第 0 个散列,$2 绑定(bind)到数组中的第 2 个散列,依此类推
con = PG::Connection.new(:dbname => "development_DB")
con.prepare("insert", stmt)
con.exec_prepared("insert", values)
con.close()

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

最佳答案

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

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!



~ 根据 alalani 回答

关于ruby-on-rails - 使用 PostgreSQL 使用 ActiveRecord 准备和执行语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com