塩焼きブログ

塩焼きに関しての研究内容を公開しています

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