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
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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.