How to show sql result on server console

2019-04-08 14:20发布

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.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-04-08 14:54

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/

查看更多
等我变得足够好
3楼-- · 2019-04-08 15:03

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}
查看更多
何必那么认真
4楼-- · 2019-04-08 15:21

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.

查看更多
登录 后发表回答