Created
September 9, 2011 07:53
-
-
Save kinopyo/1205708 to your computer and use it in GitHub Desktop.
Snippets for using mysql in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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