【Ruby】RubyからMySQLに接続方法

方法1:
require “mysql"
dbc = Mysql.real_connect('127.0.0.1′,’root’,’startnews24′,’test’)
res = dbc.query('select * from users’)
while row = res.fetch_row do
puts “#{row[0]},#{row[1]}"
end

方法2:
require 'mysql2’
client = Mysql2::Client.new(:host => “ホスト", :username => “ユーザー名",:password=>"パスワード",:database=>"DB名")
results = client.query(“select * from table名");
results.each do |hash|
puts hash.map { |k,v| “#{k} = #{v}" }.join(“, “)
end
補足:
「can’t load such file–mysql 」のエラーメッセージが出る場合、「gem install mysql 」をインストール。

Source

Posted by arkgame