Installing the MySQL Module for Ruby on Linux



I was recently working on a project where I had the need to use pure Ruby (not Rails) to insert information into a MySQL database. My Ruby installation did not have the necessary MySQL module installed so I had to install it manually. With Linux I’m generally used to doing things the hard way, which normally consists of installing the development source, configuring, making, compiling, and installing. I went through all these steps such as the ones documented here as was to the point of giving up (after 2 hours). I had thoughts of Perl and PHP flashing in my mind as my frustration grew. As a final effort I reverted to good ole Yum, which I pretty much assumed would fail:

yum install ruby-mysql

and it worked! This taught me a valuable lesson in working with Linux. In the past I’ve been accustomed to taking the difficult approach, but times have changed and Linux is becoming much more user friendly. Maybe I should rephrase that and say more developer friendly since your average user probably won’t be installing a MySQL module for Ruby. After installing I was able to successfully run the following Ruby script:

begin
db = Mysql.real_connect(”localhost”, “root”, “root_pass”, “database_name”)
puts “Server version: ” + db.get_server_info
res = db.query(”select * from tablename”)
puts “#{res.num_rows} rows returned”
rescue Mysql::Error => e
puts “Error code: #{e.errno}”
puts “Error message: #{e.error}”
puts “Error SQLSTATE: #{e.sqlstate}” if e.respond_to?(”sqlstate”)
ensure
db.close if db
end

This simply connects to the desired database, queries a table, and then prints the number of row returned.



Leave a Reply