Ruby Tutorial
From #mysql Freenode
This page contains 2 simple scripts to test MySQL with Ruby.
[edit]
Ruby MySQL
- requires
- Ruby (http://ruby-lang.org/en/)
- Ruby MySQL module (http://www.tmtm.org/en/mysql/ruby/)
- script
# testRuby-MySQL.rb - simple MySQL script using Ruby MySQL module
require "mysql"
begin
# connect to the MySQL server
dbh = Mysql.real_connect("localhost", "testUser", "testPassword", "testDB")
# get server version string and display it
puts "Server version: " dbh.get_server_info
rescue MysqlError => e
print "Error code: ", e.errno, "\n"
print "Error message: ", e.error, "\n"
ensure
# disconnect from server
dbh.close
end
- sample good output
$ ruby testRuby-MySQL.rb Server version: 5.0.22-max-log
- sample error output
$ ruby testRuby-MySQL.rb Error code: 2005 Error message: Unknown MySQL server host 'localhost1' (1) simple.rb:15: undefined method `close' for nil:NilClass (NoMethodError)
[edit]
RubyGems MySQL
- Ruby Rail users have RubyGems installed most likely.
- requires
- Ruby (http://ruby-lang.org/en/)
- RubyGems (http://docs.rubygems.org/)
- MySQL Native Bindings: sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
- script
# testRubyGem-MySQL.rb - simple MySQL script using RubyGems
require 'rubygems'
require 'mysql'
begin
# connect to the MySQL server (listening on 4306, in this example)
dbh = Mysql.real_connect('testServer', 'testUser', 'testPass', 'testDB', 4306)
res = dbh.query('select * from club')
res.each do |row|
printf "%s, %s\n", row[0], row[1]
end
printf "%d rows were returned\n", res.num_rows
rescue MysqlError => e
print "Error code: ", e.errno, "\n"
print "Error message: ", e.error, "\n"
ensure
res.free
dbh.close
end
- sample output
$ ruby testRubyGem-MySQL.rb 1, A 2, B 2 rows were returned
[edit]
References
- Using the Ruby MySQL Module (http://www.kitebird.com/articles/ruby-mysql.html)
- A One-liner with Rails and ActiveRecord (http://bohnsack.com/2005/08/15/oneliner-with-rails-and-activerecord/)

