gpt4 book ai didi

mysql - 如何从 Rails 调用 MySQL 存储过程?

转载 作者:可可西里 更新时间:2023-11-01 06:47:27 25 4
gpt4 key购买 nike

MySQL 中一个简单的存储过程:

CREATE PROCEDURE `proc01`()
BEGIN
SELECT * FROM users;
END

启动 Rails 控制台:

$ script/console
Loading development environment (Rails 2.3.5)
>> User.connection.execute("CALL proc01")
=> #<Mysql::Result:0x10343efa0>

看起来不错。但是,通过现有连接再次调用同一存储过程将导致命令不同步错误:

>> User.connection.execute("CALL proc01")
ActiveRecord::StatementInvalid: Mysql::Error: Commands out of sync; you can't run this command now: CALL proc01
from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract_adapter.rb:219:in `log'
from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/mysql_adapter.rb:323:in `execute'
from (irb):2

可以通过“重新加载!”来清除错误。控制台命令:

>> reload!
Reloading...
=> true
>> User.connection.execute("CALL proc01")
=> #<Mysql::Result:0x1033f14d0>
>>

如何从 Rails 调用 MySQL 存储过程?

最佳答案

编辑:

--

据我所知,使用 ActiveRecord::Base.connections.exec_query() 是一种MUCH 更好的方法,因为它会返回一个散列数组期望,ActiveRecord::Base.connections.execute 没有。

Documentation

--

请阅读上面的编辑,我留下下面的内容供引用。

虽然我意识到这个问题已经很久了,而且因为 ohho 发布的链接有 404',我最近遇到了同样的错误。

我能够通过执行以下操作来修复它:

result = ActiveRecord::Base.connection.execute("call example_proc()")
ActiveRecord::Base.clear_active_connections!

一旦您清除了连接,您就可以运行任何其他查询,而之前它在尝试通过 Rails 或其他存储过程访问数据库时会失败。

http://apidock.com/rails/v3.2.13/ActiveRecord/Base/clear_active_connections%21/class

--编辑:

还值得一提的是,根据 leente 在 link 上的帖子,不应将 ActiveRecord 连接存储在变量中

“不要缓存它!

不要将连接存储在变量中,因为另一个线程可能会在它已经重新 checkin 连接池时尝试使用它。请参阅:ConnectionPool "

connection = ActiveRecord::Base.connection   #WRONG

threads = (1..100).map do
Thread.new do
begin
10.times do
connection.execute("SELECT SLEEP(1)") # WRONG
ActiveRecord::Base.connection.execute("SELECT SLEEP(1)") # CORRECT
end
puts "success"
rescue => e
puts e.message
end
end
end

threads.each(&:join)

关于mysql - 如何从 Rails 调用 MySQL 存储过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2498331/

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