カテゴリー
未分類

How to connect to MySQL in Ruby

Can be easily if you use the mysql.

gem install mysql

After you have require "mysql", just run the SQL.

require "mysql"
db = Mysql::connect("host", "user", "pass", "db")
db.query("set character set utf8")
rs = db.query("SELECT * FROM tables")
count = 0
rs.each do |r|
puts r.join(",")
# or key
# puts r[2]
end
db.close

By using each_hash means, you can receive hash.

require "mysql"
db = Mysql::connect("host", "user", "pass", "db")
db.query("set character set utf8")
rs = db.query("SELECT * FROM tables")
count = 0
rs.each_hash do |r|
p r["name"]
end
db.close

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA