Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails to create and access MySQL variable

How to use Ruby on Rails to do this?

mysql> SET @t1=1, @t2=2, @t3:=4;
mysql> SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;
like image 301
wizztjh Avatar asked Oct 26 '25 08:10

wizztjh


1 Answers

Use ActiveRecord::Base.connection:

>> ActiveRecord::Base.connection.execute("SET @t1=1, @t2=2, @t3:=4;")
 => nil 
>> ActiveRecord::Base.connection.select_one(
    "SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;")
 => {"@t1"=>"1", "@t2"=>"2", "@t4 := @t1+@t2+@t3"=>"7", "@t3"=>"4"} 

For more methods you can use on this class, see the documentation here.

You can also call the connection method on any ActiveRecord class you have defined. For instance, if you have a model called Post, you can use Post.connection.execute("sql").

like image 197
wuputah Avatar answered Oct 28 '25 00:10

wuputah