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:
class DBConnector
def transaction(&block)
raise ArgumentError, "No block was given" unless block_given?
begin
client.query("BEGIN")
yield
client.query("COMMIT")
rescue
client.query("ROLLBACK")
end
end
end
So you could use like this:
DBConnector.transaction do
# your db queries here
end
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