Windows で利用する MySQL2 - Ruby

インストール

コマンドプロンプトを起動する際は、「 管理者として実行 」で起動します。

Windows で 「 MySQL Connector 」を上記のサイトの方法でインストールし、「 bundle exec rackup 」でアプリを起動したい場合、以下のコマンドを実行します。

bundle config --local build.mysql2 '--with-mysql-dir="C:\tools\MySQL"'

「 .bundle/config 」のファイルに以下のように設定が追加されます。

BUNDLE_BUILD__MYSQL2: "--with-mysql-dir=C:\\tools\\MySQL"

上記の設定ができた後に、「 bundle install 」で gem をインストールします。

MySQL2

require 'mysql2'

client = Mysql2::Client.new(
  :host => 'localhost',
  :username => 'root',
  :password => 'password',
  :encoding => 'utf8',
  :database => 'sample',
  :ssl_mode => 'disabled',
  :sslverify => 'false'
)

query = %q{select * from user}
results = client.query(query)
results.each do |row|
  puts "--------------------"
  row.each do |key, value|
    puts "#{key} => #{value}"
  end
end