如何从Rails中的MySQL存储过程获取输出参数?

编程入门 行业动态 更新时间:2024-10-25 06:22:19
本文介绍了如何从Rails中的MySQL存储过程获取输出参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从MySQL存储过程获取输出参数,让我们看下面的示例:

I'm trying to get a output parameter from MySQL stored procedure, let's have look a example below:

1在mysql中,我创建了此过程,并且可以正常工作.

1 In mysql I created this procedure and it works.

CREATE PROCEDURE sp_name (out id int) Begin select id into @id from table order by id desc limit 1; End mysql> call sp_deduct_credit_and_money(@id); Query OK, 0 rows affected (0.01 sec) mysql> select @id; +--------------+ | @id | +--------------+ | 24 | +--------------+ 1 row in set (0.00 sec)

2因此,它也可以在Rails中使用,但是不会为我返回任何值:

2 Therefore, it also works in Rails, BUT it won't return any value for me:

ActiveRecord::Base.connection.execute("call sp_name(@id)") ActiveRecord::Base.connection.execute("select @id")

这是Rails中的日志

Here is the log in Rails

(2.0ms) call sp_name(@id) (0.1ms) select @id

我的问题是,如何获取输出参数@id的返回值?

My question is that how could I get the return value of the output parameter @id?

推荐答案

我找到了一种获取输出参数,与大家共享的方法,如下所示:

I found a way to get the output parameter, to share with you guys, see below:

1创建连接

client = Mysql2::Client.new(ActiveRecord::Base.configurations[Rails.env.to_s].symbolize_keys)

2使用此连接呼叫您的sp

2 use this connection to call your sp

client.query "call sp_xxx"

3获取输出参数

result = client.query("select @output_parameter")

4返回输出

return !result.first["@output_parameter"].nil?

更多推荐

如何从Rails中的MySQL存储过程获取输出参数?

本文发布于:2023-10-28 23:17:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538053.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:存储过程   参数   Rails   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!