Ruby, ADO 이용한 SQL Server 연결
RUBY로 win32 OLE 를 이용해 ADO 연결하는 방법을 아래 소개합니다.
출처 : http://rubyonwindows.blogspot.com/search/label/sqlserver
require 'win32ole'
class SqlServer
# This class manages database connection and queries
attr_accessor :connection, :data, :fields
def initialize
@connection = nil
@data = nil
end
def open
# Open ADO connection to the SQL Server database
connection_string = "Provider=SQLOLEDB.1;"
connection_string << "Persist Security Info=False;"
connection_string << "User ID=USER_ID;"
connection_string << "password=PASSWORD;"
connection_string << "Initial Catalog=DATABASE;"
connection_string << "Data Source=IP_ADDRESS;"
connection_string << "Network Library=dbmssocn"
@connection = WIN32OLE.new('ADODB.Connection')
@connection.Open(connection_string)
end
def query(sql)
# Create an instance of an ADO Recordset
recordset = WIN32OLE.new('ADODB.Recordset')
# Open the recordset, using an SQL statement and the
# existing ADO connection
recordset.Open(sql, @connection)
# Create and populate an array of field names
@fields = []
recordset.Fields.each do |field|
@fields << field.Name
end
begin
# Move to the first record/row, if any exist
recordset.MoveFirst
# Grab all records
@data = recordset.GetRows
rescue
@data = []
end
recordset.Close
# An ADO Recordset's GetRows method returns an array
# of columns, so we'll use the transpose method to
# convert it to an array of rows
@data = @data.transpose
end
def close
@connection.Close
end
end
You can then use this class as follows:
db = SqlServer.new
db.open
db.query("SELECT PLAYER FROM PLAYERS WHERE TEAM = 'REDS';")
field_names = db.fields
players = db.data
db.close
댓글
이 글 공유하기
다른 글
-
PHP 성능 최적화를 위한 방향
PHP 성능 최적화를 위한 방향
2007.05.22 -
Ruby를 이용한 Directory 보는 구문
Ruby를 이용한 Directory 보는 구문
2007.05.19 -
Ruby App. CD-ROM 열기
Ruby App. CD-ROM 열기
2007.05.06 -
루비(Ruby) 로 초간단 프로그램 작성
루비(Ruby) 로 초간단 프로그램 작성
2007.04.29