[ next ] [ prev ] [ contents ] [ up to Appendix B -- Database Example ] Invitation To Ruby

An Even Shorter Version

  1: #!/usr/bin/env ruby
  2: 
  3: require 'dbi'
  4: 
  5: db = DBI.connect ("DBI:Pg:jim", "jim")
  6: 
  7: sql = <<-SQL
  8: SELECT email
  9: FROM person, email
 10: WHERE person.personid = email.personid
 11: AND person.nick = ? 
 12: ORDER BY nick, type
 13: SQL
 14: 
 15: db.select_all(sql, ARGV[0]) { |row|
 16:   puts row[0]
 17: }
 18: db.disconnect

An even more convient method of using the DBI is available.

  • If the SQL statement is only executed once,
    • then there is little need to "pre-compile" it.

  • Just use select_all to prep and execute the SQL in one step (lines 15-17)
    • Note that select_all with a block acts as an iterator.
    • select_all without a block will return a list of rows.

  • select_one and do are also available.
    • Use select_one when retrieving data and only expect (or want) one row.
    • Use do to execute SQL statements that do not return a result set.


[ next ] [ prev ] [ contents ] [ up to Appendix B -- Database Example ] Copyright 2002 by Jim Weirich.
All rights reserved.