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'

begin
#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
end
end
#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 ('example@example.com')")
#this is how you can edit delete the records...
rescue Exception => e
puts "I guess something went wrong. #{e}"
ensure
# clone the connection...
mysql.close if mysql
end

No comments: