Post

Ruby script to connect to MySQL database

In mysql, ruby on March 3, 2010 by danieldyba Tagged: ,

In this screencast, I’ll be writing a Ruby script to connect to a MySQL database. I’m using Ruby version 1.8.7 and the mysql gem version 2.8.1. To see this video with optimum quality, view it in HD.

Here’s the code. Save this to a file called mysql-01.rb. Find the correct directory and using the Terminal on a Mac OS X, type ruby mysql-01.rb.

require 'mysql'
begin
  db = Mysql.real_connect("localhost", "test", "testpass", "test")
  puts "Server version: " + db.get_server_info
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

If you get any errors while trying to do this, check to make sure that you have turned on your MySQL server. Also if you have not set rubygems to be the value of your RUBYOPT variable in the environment variables on your machine, you’ll get errors when you try to run the command ‘ruby mysql-01.rb’ in the Terminal window.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.