ruby 1.9.2 + mysql2 の環境構築

※ devkitのインストールとかが面倒くさい人は、mysql2 の代わりに "ruby-mysql" というDBドライバを使ってもよいでしょう。ruby ネイティブなのですぐ使えます。


走り書きですが、Windows 上での、ruby 1.9.2 + mylsql2 0.2.13のインストール手順を簡単にメモしておきます。

  • rubyinstaller 1.9.2 を使って、ruby をインストール。手元の環境ではruby 1.9.2-p180 を使ってます。
  • rubyinstaller の devkit をインストール。 1.9.2-p180 に対応したバージョンをアーカイブリストから探してくる。
  • MySQLのインストールは、C\mysql\mysql51 とか、パスに空白が含まれない場所にする。
    • なお、データフォルダは、どこでもよい。
  • そのあと、devkit.bat を使って、コマンドプロンプトgccの環境を設定する。
  • そして、gem コマンドを実行し、mysql2をインストールする。もしかしたら、 --with-mysql-lib はなくても成功するかもしれない。
> gem install mysql2 -v 0.2.13 -- '--with-mysql-include="c:\mysql\mysql51\include" --with-mysql-lib="C:\mysql\mysql51\lib" --with-opt-lib="C:\mysql\mysql51\lib\opt"

mysql2 のバージョンですが、rails 3.0 系であれば、0.2.7 以降、0.3未満を使う必要があります。

0.3以上はRails 3.1 から使えるらしいです。

補足

もしインストールに失敗したら、"C:\Ruby192\lib\ruby\gems\1.9.1\gems\mysql2-0.2.11\ext\mysql2" とかの gem_make.out や mkmf.log に、ログが残ってます。

オプション指定に失敗してると、以下のように実行結果が表示されます。

>gem install mysql2 -v 0.2.12
Fetching: mysql2-0.2.12.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
        ERROR: Failed to build gem native extension.

        C:/Ruby192/bin/ruby.exe extconf.rb
checking for rb_thread_blocking_region()... yes
checking for main() in -llibmysql... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/Ruby192/bin/ruby
        --with-mysql-dir
        --without-mysql-dir
        --with-mysql-include
        --without-mysql-include=${mysql-dir}/include
        --with-mysql-lib
        --without-mysql-lib=${mysql-dir}/lib
        --with-libmysqllib
        --without-libmysqllib


Gem files will remain installed in C:/Ruby192/lib/ruby/gems/1.9.1/gems/mysql2-0.
2.12 for inspection.
Results logged to C:/Ruby192/lib/ruby/gems/1.9.1/gems/mysql2-0.2.12/ext/mysql2/g
em_make.out