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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With