Hello, ODBC(Ruby) World!

Posted on 9月 23rd, 2012 by cx20

DBI

ODBC(Open Database Connectivity)は、マイクロソフト社が提唱した DBMS 接続用の API 仕様である。
DBMS の差異は ODBC ドライバによって吸収される為、ODBC の手順にしたがってプログラムを作成すれば、基本的な差異を意識せず、プログラムすることができる。

ODBCドライバ ファイル
Microsoft Access Driver (*.mdb) ODBCJT32.DLL
Microsoft Text Driver (*.txt; *.csv) ODBCJT32.DLL
Microsoft Excel Driver (*.xls) ODBCJT32.DLL
Microsoft dBase Driver (*.dbf) ODBCJT32.DLL
Microsoft ODBC for Oracle MSORCL32.DLL
Microsoft Paradox Driver (*.db ) ODBCJT32.DLL
SQL Server SQLSRV32.DLL
Microsoft Access Driver (*.mdb, *.accdb) ACEODBC.DLL
SQL Server Native Client 10.0 SQLNCLI10.DLL

DBI は Ruby 向けの Database Interface(API)である。
DBI 用 ODBC ドライバを介することで、様々な DBMS への接続が可能となっている。

ソースコード(Ruby + DBI + ODBC + SQL Server)

require 'rubygems'
require "dbi"
dbh = DBI.connect("DBI:ODBC:Driver={SQL Server};Server=(local);DATABASE=master", "sa", "P@ssW0rd")
sth = dbh.prepare("SELECT 'Hello, DBI World' AS Message")
sth.execute()
while row = sth.fetch do
    print "Message", "n";
    print "-------------------n";
    print row[0]
end
sth.finish
dbh.disconnect

ライブラリ導入方法

C:¥> gem install dbi
C:¥> gem install dbd-odbc

以下のエラーが出る場合は、odbc.so と odbc_utf8.so が足りていない可能性がある為、ODBC Binding for Ruby より i386-msvcrt-ruby-odbc.zip を入手し、%RUBY_HOME%librubysite_ruby1.8i386-msvcrt にコピーする必要がある。

C:/ruby-1.8/lib/ruby/gems/1.8/gems/dbi-0.4.5/lib/dbi.rb:300:in `load_driver': Unable to load driver 'ODBC' (underlying error: uninitialized constant DBI::DBD::ODBC) (DBI::InterfaceError)
        from C:/ruby-1.8/lib/ruby/1.8/monitor.rb:242:in `synchronize'
        from C:/ruby-1.8/lib/ruby/gems/1.8/gems/dbi-0.4.5/lib/dbi.rb:242:in `load_driver'
        from C:/ruby-1.8/lib/ruby/gems/1.8/gems/dbi-0.4.5/lib/dbi.rb:160:in `_get_full_driver'
        from C:/ruby-1.8/lib/ruby/gems/1.8/gems/dbi-0.4.5/lib/dbi.rb:145:in `connect'
        from hello.rb:3

なお、2012.09 現在、1.9 版のライブラリは提供されていない模様。

実行方法(Windows)

C:¥> ruby hello.rb

実行結果

Message
-----------------
Hello, DBI World!

Tags:

Categories: ODBC, Ruby

コメントを残す

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

WP-SpamFree by Pole Position Marketing