How to show sql result on server console

Mellon picture Mellon · Nov 11, 2011 · Viewed 7.9k times · Source

In Rails v2.3 , Ruby 1.8, if I run a sql statement with following code in my model class:

ActiveRecord::Base.connection.execute("select count(*) from cars;")

How can I show the query result in server console?

I tried :

rslt = ActiveRecord::Base.connection.execute("select count(*) from cars;")
p rslt

but it only returns me "MySQL result object" on the server console, not the exact result.

Answer

Iuri G. picture Iuri G. · Nov 11, 2011

There are couple ways to get mysql "answer" from your query. you can call each and it will iterate over each row (just one row - count in your case). take a look at mysql gem docs to see other available methods such as each_hash and all_hashes.

rslt = ActiveRecord::Base.connection.execute("select count(*) from cars;")
rslt.each {|mysql_result| puts mysql_result}