Executing SQL commands in Rails

Most of the times, ActiveRecord’s helpers to access database info is all you need; sometimes, you want to do some hacky stuff.

For example, I had to figure out a database’s timezone and schema but I had no shell access to the server. So I ran this used Base.connection.execute and fetch_row to get the result


q=ActiveRecord::Base.connection.execute 'SELECT NOW();'
=> #
>> q.fetch_row
=> ["2009-10-20 17:30:49"]
>> Time.now
=> Tue Oct 20 10:32:02 -0700 2009
>>q.free

You can basically run any SQL query you want with these two methods. Now go crash some servers!

Note: You should also free your result to free up memory. Thanks Emmanuel.

2 Comments

  1. Posted October 30, 2009 at 3:20 am | Permalink

    You may want to free your results after fetching. See http://www.fngtps.com/2008/11/free-result-after-using-activerecord-base-connection-execute

    Greets!

  2. Posted October 30, 2009 at 4:24 pm | Permalink

    Thanks Emmanuel, I just updated it to reflect that.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">