LoginSignup
4
5

More than 5 years have passed since last update.

RailsでMysqlのユーザー変数を利用する方法

Posted at

Rails4でMysql2を利用している前提で。

class MyModel < ActiveRecord::Base

  def get_client
    params = ActiveRecord::Base.configurations[Rails.env.to_s].symbolize_keys
    return Mysql2::Client.new(params)
  end

  def test_query
    query =<<SQL
set @p=200;
set @c=0;
select @p, @c;
SQL

    client = get_client

    # client.query("set @p=200; set @c=0; select @p, @c")とすると構文エラーになってしまうため、1行ずつ実行する
    queries = query.split(/;/)
    queries.each do |line|
       result = client.query(line)
    end

    result.first # {"@p"=>200, "@c"=>0} 
  end
end

参考
http://stackoverflow.com/questions/7480579/how-to-get-output-parameters-from-mysql-stored-procedure-in-rails

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5