5.3. Database access using DBI

5.3.1. Component-izing of DBI::DatabaseHandle

When accessing a database using DBI, DBI::DatabaseHandle instance is created by DBI.connect method. By treating this DBI::DatabaseHandle as a component in S2Container, it is injected to some components, such as Dao component.

The s2comp method is used for creation of a DBI::DatabaseHandle component. A constructor block is passed to the s2component method and DBI.connect method is called within the block. Moreover, DBI::DatabaseHandle.disconnect is executed in the destructor block.

component_info = s2comp(:class => DBI::DatabaseHandle, :name => :dbh, :autobinding => :none) {
  next DBI.connect("dbi:SQLite3:sample.db")
}

component_info.destructor {|dbh|
  dbh.disconnect
}

Let's create CdDao which uses a DBI::DatabaseHandle component.

module Example
  class Dao
    s2comp

    def initialize
      @dbh = nil             # DBI::DatabaseHandle instance will be injected
    end

    def find_by_name(name)
      sth = @dbh.prepare("SELECT * FROM people WHERE name = ?")
      sth.execute(name)
      sth.fetch {|row|
        printf "ID: %d, Name: %s, Height: %.1f\n", row[0], row[1], row[2]
      }
      sth.finish
    end
  end
end

Please create the following executable files.

require 'rubygems'
require 'dbi'
require 's2container'
require 'example'

component_info = s2comp(:class => DBI::DatabaseHandle, :name => :dbh, :autobinding => :none) {
  s2logger.info(File.basename(__FILE__)){"Database handle connected."}
  next DBI.connect("dbi:SQLite3:sample.db")
}

component_info.destructor {|dbh|
  s2logger.info(File.basename(__FILE__)){"Database handle disconnected."}
  dbh.disconnect
}

container = s2app.create
begin
  dao = container.get(Example::Dao)
  dao.find_by_name('hoge')
rescue => e
  s2logger.fatal(e.class.name){"#{e.message} #{e.backtrace}"}
ensure
  container.destroy
end
[Note]NOTE

This Example is located in example/example13



© Copyright The Seasar Foundation and the others 2008-2009, all rights reserved.