Step By Step Guide to Using MySQL in Ruby

This is an article on Step By Step Guide to Using MySQL in Ruby in Ruby on Rails.

MySQL is a hot favourite RDBMS, primarily when developing web applications, and Ruby is an emerging language in the web development business. I have earlier discussed about working with MySQL in many other languages like Python, Perl, C, etc. In this article we will be looking at installation and usage of the MySQL library for Ruby.

## loop through the result set## this returns each row as hash, the field name being the keyrs.each_hash(with_table=false) { |h| puts h['name']}

## alternate way to iterate through the result setn_rows = rs.num_rows

n.rows.times do puts rs.fetch_row.join(" ")end

con.close

Advanced Usage

In advanced usage we will look at prepared statements which improve the efficiency and the security, provide features like place holders, and error handling. Unless you are a completely new to programming the sample code below will be more than enough to get you started in enabling database connections in your Ruby program.

Code: Ruby

#!/usr/bin/ruby

require 'rubygems'require 'mysql'

## block where the code runs, so that the error may be trappedbegin ## connect to the mysql server con = Mysql.new('localhost', 'myuser', 'myPas*', 'my_db')

## execute a query prepared_statement = con.prepare('select * from people where age > ?') prepared_statement.excute 3

## loop through the result set ## this returns each row as hash, the field name being the key prepared_statement.each { |h| puts h.join(" ") }