I've started using mysql2
gem. I'm trying to figure out a few basic things - one of them is how to explicitly perform transactions (for batch operations, like multiple INSERT/UPDATE queries).
In the old ruby-mysql
, this was my approach:
client = Mysql.real_connect(...)
inserts = [
"INSERT INTO ...",
"UPDATE .. WHERE id=..",
# etc
]
client.autocommit(false)
inserts.each do |ins|
begin
client.query(ins)
rescue
# handle errors or abort entirely
end
end
client.commit
I couldn't find much in the docs - how can the same be done with mysql2
?
I just have done a implementation:
So you could use like this:
Using Bruno's template, then adding a transaction status indicator:
Interacting with #transaction:
This question made me curious, so I tracked down how Ruby on Rails handles transactions, and I found this code:
Have you tried executing a
begin
andcommit
statement around your other statements?