Ruby MySQL Tutorial
This brief Ruby MySQL Tutorial shows you how you can connect to MySQL in Ruby. MySQL support in Ruby was made possible by Tomita Masahiro. He has developed a pure Ruby binding called Ruby/MySQL.
We need to install the same on our PC and the installation (you need to be connected to the internet and it takes some time) is as shown below:
C:\>gem install mysql
Bulk updating Gem source index for: http://gems.rubyforge.org
Select which gem to install for your platform (i386-mswin32)
1. mysql 2.7.3 (mswin32)
2. mysql 2.7.1 (mswin32)
3. mysql 2.7 (ruby)
4. mysql 2.6 (ruby)
5. Skip this gem
6. Cancel installation
> 1
Successfully installed mysql-2.7.3-mswin32
Installing ri documentation for mysql-2.7.3-mswin32...
Installing RDoc documentation for mysql-2.7.3-mswin32...
C:\> This installs mysql-2.7.3-mswin32 driver which is faster and supports MySQL 5.0.51a and later. Also, it requires Ruby 1.8.6. The documentation for this driver is here.
I will assume that you've already installed MySQL 5 or above on your PC and that you have it running and are familiar with the basics.
First, ensure that your MySQL server is running. If not, you can start it by typing this at the command prompt:
C:\>mysqld Now, open a new command window run the mysql client program from the command line, as:
C:\>mysql --user=root mysql You should get the mysql prompt. Next, create a database ruby as:
mysql> create database ruby;
Query OK, 1 row affected (0.02 sec) Next, create a table student in the database ruby as:
mysql> use ruby;
create table student (id VARCHAR(2), name VARCHAR(20), rank VARCHAR(2)); Populate the above table with some data and as a first exercise we try to connect to the MySQL server and print all the names in the table student. Program p078rubymysql.rb
require 'mysql'
#my = Mysql.new(hostname, username, password, databasename)
con = Mysql.new('localhost', '', '', 'ruby')
rs = con.query('select * from student')
rs.each_hash { |h| puts h['name']}
con.close It is as simple as that. You can explore this api further.
Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them.