Monday, September 28, 2009

Ruby Mysql database connectivity

In this section I am going to tell you how do you get connected your MySQL database using Ruby.

Make sure that you have install mysql adapter
To verify you mysql file go to command prompt type irb -> require 'mysql' if it's return true that means the file is loaded.

Now use your fav editor let say scite.

require 'rubygems'
require 'mysql'

#establish a connection.
mysql = Mysql.real_connect("hostname(e.g - localhost)", "username", "password", "databasename")
result = mysql.query("SELECT * FROM USERS;")
result.each do |row|
row.each do |col|
puts col
#the col object will return the value from the users table.
# if you want to insert a record. then
mysql.query("INSERT INTO users (email) VALUES ('')")
#this is how you can edit delete the records...
rescue Exception => e
puts "I guess something went wrong. #{e}"
# clone the connection...
mysql.close if mysql

No comments: