MySQL Ruby Gem: `require’: no such file to load — mysql (LoadError)

I am starting to learn ruby and am working on a test script to import some data into a MySQL database. I am using the below code found on kitebird.com to first get the MySQL connection from Ruby working. The code was producing an error which I figured might be because I installed the MySQL Ruby gem instead of installing the MySQL Ruby module from source.

The below code attempts to connect to the MySQL server to return the MySQL server version.

Code:

ruby

require'mysql'

begin

# connect to the MySQL server

dbh = Mysql.real_connect("localhost", "user", "password", "database")

# get server version string and display it

puts"Server version: "+ dbh.get_server_info

rescueMysql::Error=> e

puts"Error code: #{e.errno}"

puts"Error message: #{e.error}"

puts"Error SQLSTATE: #{e.sqlstate}"if e.respond_to?("sqlstate")

ensure

# disconnect from server

dbh.closeif dbh

end

Running this code with the MySQL gem installed returned the below error.

Error:

bash

test.rb:1:in `require': no such file to load -- mysql (LoadError)

from test.rb:2

This was telling me it was having trouble loading the mysql module so I figured out that the rubygems gem must be loaded first. The below code only adds one line to the beginning of the script to make things work properly.

ruby

require'rubygems'

require'mysql'

begin

# connect to the MySQL server

dbh = Mysql.real_connect("localhost", "user", "password", "database")

# get server version string and display it

puts"Server version: "+ dbh.get_server_info

rescueMysql::Error=> e

puts"Error code: #{e.errno}"

puts"Error message: #{e.error}"

puts"Error SQLSTATE: #{e.sqlstate}"if e.respond_to?("sqlstate")

ensure

# disconnect from server

dbh.closeif dbh

end

Now when running this code I get the following result.

bash

[user@server ~]$ ruby test.rb

Server version: 5.0.45

Obviously this is now returning the MySQL server version which on the server the script is being run on happens to be 5.0.45.