简体   繁体   English

从Rails 3调用MySQL存储过程(返回结果集)时出错

[英]Error while invoking MySQL Stored procedure(that returns resultset) from Rails 3

I am invoking a stored procedure (MySQL) from my model. 我正在从模型中调用存储过程(MySQL)。 This stored procedure returns a resultset, but i get this error... 此存储过程返回一个结果集,但出现此错误...

Mysql2::Error: PROCEDURE my_db.sp_venue_nearby_with_questions can't return a result set in the given context:.... Mysql2 :: Error:过程my_db.sp_venue_nearby_with_questions无法在给定上下文中返回结果集:....

Here's the rails code i use - 这是我使用的Rails代码-

connection.select_all("call sp_some_proc()")

I have tried "connection.execute" as well, that fails as well. 我也尝试过“ connection.execute”,但是也失败了。 I have successfully been able to invoke another stored proc from my model, but that one does not return a resultset. 我已经能够成功地从我的模型中调用另一个存储的proc,但是那个不会返回结果集。

I tried the same thing with the MySQL 2 gem which is used by default in Rails 3 and got a similar error. 我尝试了在Rails 3中默认使用的MySQL 2 gem进行同样的操作,并得到了类似的错误。 The problem is that the MySQL 2 gem by default does not use the MULTI_STATEMENTS which is needed when you want to get a result set back from the procedure. 问题是默认情况下,MySQL 2 gem不使用MULTI_STATEMENTS,当您要从过程中获取结果集时需要​​使用MULTI_STATEMENTS。

After some investigation I've decided to stick with the original MySQL gem ( adapter:mysql instead of adapter:mysql2 in database.yml ) which seems to work fine also in Rails 3. 经过一番调查后,我决定坚持使用原始的MySQL gem(在database.yml adapter:mysql而不是adapter:mysql2 ),在Rails 3中似乎也可以正常工作。

Here is what I do in order to get the result from a stored procedure to an ActiveRecord class: 这是为了将结果从存储过程获取到ActiveRecord类的操作:

db = ActiveRecord::Base.connection.raw_connection
entries = Entry.find_by_sql( 'CALL sp_get_all_entries()' )

# we need to flush the result set otherwise following SQL statements cannot be processed
db.next_result if ( db.more_results? )

Now the rows returned from the stored procedure will be available on the entries objects, eg 现在,从存储过程返回的行将在entry对象上可用,例如

entries.each do |entry|
    puts entry.name
    puts entry.extra_column_from_sp
end

Note that you can add extra columns in the SP. 请注意,您可以在SP中添加额外的列。 Those extra columns will always be of type "String" so you might need to convert them, eg to a date. 这些额外的列将始终为“字符串”类型,因此您可能需要将其转换为例如日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM