-->

How to show sql result on server console

2019-04-08 14:56发布

问题:

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.

回答1:

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}


回答2:

You can just use the to_a method on your result, like so:

result = connection.execute(sql)
result.to_a

This will return (and show if in console) what you're looking for.



回答3:

It depends on the environment you are using currently. For development the default logger level is debug, for production it's info level. You can use it this way:

class HomeController < ActionController::Base
  def index
    rslt = ActiveRecord::Base.connection.execute("select count(*) from cars;")
    logger.info "#{rslt}"
  end
end

You can read more about rails logging on Mike Naberezny's blog: http://mikenaberezny.com/2007/02/24/rails-logging-tips/