Free result after using ActiveRecord::Base.connection.execute
Just a quick warning: when you use ActiveRecord::Base.connection.execute you get a Mysql::Result instance, this is a very thin wrapper around the actual result returned from libmysqlclient. This means you have to free the memory of the result table, failing to do so will result in erratic query times because somewhere a garbage collector will do it for you.
class Person < ActiveRecord::Base
# Returns the last name of someone given the ID
def self.last_name(id)
result = connection.execute("SELECT last_name FROM people" +
" WHERE id = %d" % id)
last_name = result.fetch_row.first
result.free
last_name
end
end
When you want to select a number of entire rows, you can use the already safe select_rows.
Comments
Add your comment
In order to fight spam on this blog, posting comments from a browser without javascript is currently not supported.
Subscribe
Matthijs Langenberg about 2 hours later: (delete | show email)
Manfred, thanks for the heads up! ¶
Alex about 19 hours later: (delete)
note that ActiveRecord::Base.connection.execute will not always return a Mysql::Result instance, e.g. on any INSERT INTO, CREATE TABLE, DROP TABLE, DELETE FROM etc it will return nil instead.
I assume it will return an object *only* on SELECT querys. ¶
Manfred Stienstra about 19 hours later: (delete)
Right, execute doesn't always return a Result, only with queries that return a table like SELECT, SHOW, etc. ¶
Jing 3 days later: (delete | show email)
Thanks for the reminder. very helpful. ¶