Skip to content

Instantly share code, notes, and snippets.

@kinopyo
Created September 9, 2011 07:53
Show Gist options
  • Save kinopyo/1205708 to your computer and use it in GitHub Desktop.
Save kinopyo/1205708 to your computer and use it in GitHub Desktop.
Snippets for using mysql in ruby
require "mysql"
# more examples:
# http://www.kitebird.com/articles/ruby-mysql.html
hostname = 'localhost'
username = 'yourname'
password = 'password'
database = 'mysql'
port = 3306
begin
# connect
db = Mysql::connect(hostname, username, password, database, port)
sql = "select id, nickname from users limit 10"
res = db.query(sql);
# each hash approch
res.each_hash do |h|
p "#{h['id']}, #{h['nickname']}"
end
# each approach
res2 = db.query(sql);
res2.each do |row|
p row.join(",")
p row[0]
end
# Mysql::Result
p res.class
# Number of rows
p "Number of rows: #{res.num_rows}"
rescue Mysql::Error => e
p "Error message: #{e.error}, code: #{e.errno}"
ensure
# disconnect from server
db.close if db
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment