ruby連線Oracle

333111444發表於2008-11-14

ruby的速度,ruby的靈巧,ruby的簡潔,給許多開發人員一個驚喜,rails功不可沒,但是ruby本身的優秀也是名不虛傳。

別的不說了,以下是蒐羅出來的ruby與資料庫互動小樣。格式與Java也差不多,SQL語句嘛,本身就是挺羅嗦的事。不知道ruby什麼時候也能整個orm出來,呵呵。

#create
 require 'dbi'
  dbh = DBI.connect('DBI:OCI8:ORCL', 'hr', 'hr')
  dbh.do("CREATE TABLE states (
  id CHAR(2) PRIMARY KEY,
  name VARCHAR2(15) NOT NULL,
  capital VARCHAR2(25) NOT NULL)")
  dbh.disconnect

#insert
require 'dbi'
  dbh = DBI.connect('DBI:OCI8:ORCL', 'hr', 'hr')
  sqlInsert = "INSERT INTO states (id, name, capital)
  VALUES (?, ?, ?)"
  dbh.do(sqlInsert, "AL", "Alabama", "Birmingham")
  dbh.do(sqlInsert, "AZ", "Arizona", "Phoenix")
  dbh.do(sqlInsert, "CO", "Colorado", "Denver")
  dbh.do(sqlInsert, "FL", "Florida", "Tallahassee")
  dbh.do(sqlInsert, "MA", "Maine", "Augusta")
  dbh.do(sqlInsert, "PA", "Pennsylvania", "Philadelphia")
  dbh.do(sqlInsert, "UT", "Utah", "Salt Lake City")
  dbh.do(sqlInsert, "WA", "Washington", "Seattle")
  dbh.do(sqlInsert, "WY", "Wyoming", "Cheyenne")
  dbh.commit
  dbh.disconnect

[@more@]

#update
 require 'dbi'
  dbh = DBI.connect('DBI:OCI8:ORCL', 'hr', 'hr')
  sqlCapitalsUpdate = "UPDATE states SET capital = ? WHERE id = ?"
  dbh.do(sqlCapitalsUpdate, "Montgomery", "AL")
  dbh.do(sqlCapitalsUpdate, "Harrisburg", "PA")
  dbh.do(sqlCapitalsUpdate, "Olympia", "WA")
  dbh.do("UPDATE states SET id = 'ME' WHERE name = 'Maine'")
  dbh.commit
  dbh.disconnect
#query
require 'dbi'
  dbh = DBI.connect('DBI:OCI8:ORCL', 'hr', 'hr')
  rs = dbh.prepare('SELECT * FROM states')
  rs.execute
  while rsRow = rs.fetch do
  p rsRow
  #Alternative output: puts rsRow
  #Alternative output: pp rsRow
  end
  rs.finish
  dbh.disconnect

#Ruby DBI 提供了更好的輸出格式。清單 5 和 6 顯示使用 DBI 分別以表格和 XML 格式輸出相同的查詢結果。清單 5 和 6 中的程式碼不僅顯示了 DBI::Utils 輸出格式功能的用法,還顯示了與清單 4 略微不同的獲取和操作結果集的方法。

#  清單 5 queryStatesTableFormatter.rb

  require 'dbi'
  dbh = DBI.connect('DBI:OCI8:ORCL', 'hr', 'hr')
  rs = dbh.execute('SELECT * FROM states')
  rows = rs.fetch_all
  column_names = rs.column_names
  rs.finish
  DBI::Utils::TableFormatter.ascii(column_names, rows)
  dbh.disconnect
  Listing 6: queryStatesTableXML.rb
  require 'dbi'
  dbh = DBI.connect('DBI:OCI8:ORCL', 'hr', 'hr')
  rs = dbh.execute('SELECT * FROM states')
  states_rows = rs.fetch_all
  rs.finish
  DBI::Utils::XMLFormatter.table(states_rows)
  dbh.disconnect

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12058779/viewspace-1013385/,如需轉載,請註明出處,否則將追究法律責任。

相關文章