2013年11月5日火曜日

Getting Started With Ruby/DBI + Oracle on Mac

1. Download Oracle Instant Client from the download page.

  • instantclient-basic-macos.x64-11.2.0.3.0.zip
  • instantclient-sdk-macros.x64-11.2.0.3.0.zip

2. Unzip the zip files.

$ cd /usr/local
$ unzip instantclient-basic-macro.x64-11.2.0.3.0.zip
$ unzip instantclient-sdk-macros.x64-11.2.0.3.0.zip

3. Create a symbolic link to the libclntsh library.

$ cd instantclient_11_2
$ ln -s libclntsh.dylib.11.1 libclntsh.dylib

4. Prepare a configuration file for Oracle clients.

$ vi /etc/tnsnames.ora

your-service-name =
  (DESCRIPTION =
    (ADDRESS =
      (PROTOCOL = TCP)
      (HOST = your-host-name)
      (PORT = 1521)
    )
    (CONNECT_DATA =
      (SERVICE_NAME = your-service-name)
    )
  )

5. Set up some environment variables.

$ export DYLD_LIBRARY_PATH=/usr/local/instantclient_11_2
$ export NLS_LANG=Japanese_Japan.AL32UTF8
$ export TNS_ADMIN=/etc/

6. Install DBI and the driver for Oracle.

$ gem install dbi
$ gem install ruby-oci8

7. Write a test script.

$ vi test.rb

#!/usr/bin/env ruby

require 'rubygems'
require 'dbi'

user = 'your-user-name'
password = 'your-password'
service_name = 'your-service-name'


DBI.connect("DBI:OCI8:#{service_name}", user, password) do |dbh|
  row = dbh.select_one("SELECT * FROM v$version")
  puts "Server version = #{row[0]}"
end

8. Run the test script and it'll show a result like below.

Server version = Oracle Database 11g Release 11.2.0.1.0 - 64bit Production