How to show sql result on server console

心已入冬 提交于 2019-12-21 17:18:21

问题


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/



来源:https://stackoverflow.com/questions/8096393/how-to-show-sql-result-on-server-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!