我直接使用 Model.connection 在 Rails 中运行 MySQL 存储过程。所有数据都正确插入数据库并按预期返回,但我在测试中遇到以下错误:
ActiveRecord::StatementInvalid: Mysql2::Error: 命令不同步;你现在不能运行这个命令:ROLLBACK
ActiveRecord::StatementInvalid: Mysql2::Error: 命令不同步;你现在不能运行这个命令:BEGIN
暂定一:
Model.connection.transaction do
result = Model.connection.select_value("CALL myStoredProcedure(...);")
end
暂定二:
Model.connection.begin_db_transaction
result = Model.connection.select_value("CALL myStoredProcedure(...);")
Model.connection.commit_db_transaction
暂定3:
result = Model.connection.select_value("CALL myStoredProcedure(...);")
Model.clear_active_connections!
尝试 #3 导致“ActiveRecord::StatementInvalid:Mysql2::Error:命令不同步;您现在无法运行此命令:BEGIN”消失。命令 ROLLBACK 的错误仍然存在。
我做错了什么?
谢谢
最佳答案
我怀疑您的模型连接试图同时运行相互冲突的查询。不要使用 Model.connection.select_value
,而是尝试使用 ActiveRecord::Base.connection.execute
:
result = ActiveRecord::Base.connection.execute "CALL myStoredProcedure(...);"
ActiveRecord::Base.clear_active_connections!
关于mysql - Rails:Mysql2::错误:命令不同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32138043/