Ruby Tutorial

From Hashmysql
Jump to: navigation, search

This page contains 2 simple scripts to test MySQL with Ruby.

Ruby MySQL

  • requires
  1. Ruby
  2. Ruby MySQL module
  • 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)

RubyGems MySQL

Ruby Rail users have RubyGems installed most likely.
  • requires
  1. Ruby
  2. RubyGems
  3. 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


References