Tag: quickstarts

Quick start to Ruby with MySQL

Posted by – December 14, 2010

I’ve done Ruby on Rails with MySQL but never done done Ruby with MySQL. I just did this last week to check a small thing. I didn’t want to establish the whole Rails’s process. I takes a lot of memory.

Let’s do a quick start.

Install a driver first. You can get one that’s written by C or Ruby. If you got gem then that’s easy.

$ sudo gem install mysql

It’s written by C

It’s quite easy to start. Require ‘mysql’ then create a connection to the database and then query. If install by gem, just require ‘rubygems’ first.

require 'rubygems'
require 'mysql'
db = Mysql::new("host", "user", "passwd", "db")
res = db.query("select * from mytable")
res.each do |row|
  puts "id: #{row[0]}"

and this is what I got

id: 1
id: 2
id: 3
id: 4

Looks simple. The index of an element in an array is sorted by the sequence of columns in the table.

Or you can get the column names instead of the indexes by each_hash

res.each_hash do |row|
  puts "id: #{row['id']}"

More information at the pages of the driver.