views:

402

answers:

3

Hi,

I want to run a raw SQL query as following:

ActiveRecord::Base.connection.execute(some_query);

Can I capture any errors that happen while executing the query? If yes, how? Does execute returns anything? It doesn't say in the documentation.

Cheers

A: 

I think I found the answer. Execute statement returns the error that it receives from the database and that can be captured in a variable and displayed.

Priyank
+2  A: 

You can rescue errors as normal. For example:

begin
  ActiveRecord::Base.connection.execute(some_query)
rescue
  # do stuff with exception
end

Have a look at the MySql (for example) adapter's code to see what's going on.

In this case, execute returns a MySql::Result object.

Andy Stewart
+1  A: 

execute method is typically implemented by respective database adapters and returns Result object from respective database libraries. So, if you are using Mysql the return value will be of type Mysql::Result.

Typically, if there is an error, the method will simply raise an exception which can be rescued.

Hemant Kumar