Ruby MySQL Transaction Example

rubyHere is a simple tutorial showing how to implement transactions in Ruby with MySQL.

The code uses The MySQL2 Gem. We are showing the insert of 2 records into the customers table of a database. If either insert fails, both will be rolled back.

require "mysql2"
client_mysql = Mysql2::Client.new(:host =>; "localhost", :username =>; "my_user", :password =>; "my_password")
client_mysql.query('begin')
begin
mysql_query_insert_customer1 = 'INSERT INTO MyDatabase.CustomersTable (name, phoneNumber, address) VALUES ("FSB", "888-555-5555", "322 Firstsearch Way")'
result_insert_mysql = client_mysql.query mysql_query_insert_customer1
mysql_query_insert_customer2 = 'INSERT INTO MyDatabase.CustomersTable (name, phoneNumber, address) VALUES ("FSG", "887-555-5555", "322 Firstsearch Road")'
result_insert_mysql = client_mysql.query mysql_query_insert_customer2
rescue Exception => e
puts "+++++++ DB ERROR - ROLLING BACK ++++++++"
puts e #print the MySQL Error
client_mysql.query('rollback') #rollback both of our insert statements
exit #exit the script/app (you might want a softer touch)
end
client_mysql.query('commit') #commit the changes to the DB
client_mysql.close