Ruby connect to SQL server native client
尝试了一天,终于找到可以连接SQL Server的方法了。
第一种方法,使用win32ole连接。
特别注意红色部分哦,网络上面很多人报出来的错误都是因为连接的字符串的Provider有问题,修改为红色的值,就可以和SQL server的native client连接成功了。
require 'win32ole'
class SqlServer
# This class manages database connection and queries
attr_accessor :connection, :data, :fields
attr_writer :username, :passworddef initialize(host, username = 'sa', password='')
@connection = nil
@data = nil
@host = host
@username = username
@password = password
enddef open(database)
# Open ADO connection to the SQL Server database
connection_string = "Provider=SQLNCLI;"
connection_string << "Persist Security Info=True;"
connection_string << "User ID=#{@username};"
connection_string << "password=#{@password};"
connection_string << "Initial Catalog=#{database};"
connection_string << "Data Source=#{@host};"
connection_string << "Network Library=dbmssocn"
@connection = WIN32OLE.new('ADODB.Connection')
@connection.Open(connection_string)
enddef 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
enddef close
@connection.Close
end
enddb = SqlServer.new('hostip', 'username', 'password')
db.open('databasename')
warmlead_url = "select * from table'"
db.query(warmlead_url)puts field_names = db.fields
cust = db.data
puts cust.size
puts cust[0].inspect
db.close
第二种方法,使用dbi连接。
按照如下步骤先配置Ruby环境,然后再运行脚本。
1. 先去下载ruby-dbi下面的dbi-0.4.3.gem和dbi-0.1.0.tar.gz,下载网址为http://rubyforge.org/frs/?group_id=234&release_id=4323
2. 安装dbi-0.4.3.gem
gem install dbi-0.4.3.gem
3. 解压dbi-0.1.0.tar.gz,寻找ADO.rb文件。dbi-0.1.0.tar.gz包解压后的路径下面寻找(bdi-0.1.0/lib/dbd/ADO.rb
)
4. 手动创建ADO文件夹,创建好之后的路径为c:/ruby/lib/ruby/site_ruby/1.8/DBD/ADO
5. 拷贝ADO.rb文件到步骤4中创建好的文件夹下面
6. 使用下面的Ruby代码连接SQL Server Native Client, 特别注意红色的部分。
require 'dbi'
class Server
attr_reader :name
def initialize(name, username, password, database)
@server_name=name
@username = username
@password = password
@database = database
@dbh=DBI.connect("DBI:ADO:Provider=SQLNCLI;Data Source=#{name};Persist Security Info=False;User ID=#{@username};password=#{@password};Initial Catalog=#{database};")
end
def databases
db=Array.new
@dbh.select_all('SELECT name FROM master.sys.databases ORDER BY 1') do | row |
db.<< Database.new(@dbh,row[0])
end
db
end
endclass Database
attr_reader :name
def initialize(dbh,name)
@dbh=dbh
@name=name
end
endserver=Server.new("hostname","username","password","database_name")
server.databases.each {|x| puts x.name}