日期:2014-05-16  浏览次数:20642 次

Ruby连接数据库技术2
#以下为MSSQL数据库连接类文件,用于Ruby引用连接数据库。

class SqlServer
# This class manages database connection and queries
attr_accessor :connection,:data,:fields
attr_writer :username, :password
def initialize(host, username = 'sa', password='')
@connection = nil
@data = nil
@host = host
@username = username
@password = password
end
def open(database)
# Open ADO connection to the SQL Server database
connection_string = "DRIVER=SQL Server;"
connection_string << "SERVER=#{@host};"
connection_string << "UID=#{@username};"
connection_string << "PWD=#{@password};"
connection_string << "APP=Microsoft Office 2003;WSID=user3130.fpihz.com;"
connection_string<<"DATABASE=#{database}"
@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 execute(sql)   
    @connection.Execute(sql)   
  end
def close
@connection.Close
end
end