Ruby connect to SQL server native client

來源:互聯網
上載者:User

嘗試了一天,終於找到可以串連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, :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 = "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)
    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

db = 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
end

class Database
attr_reader :name
def initialize(dbh,name)
  @dbh=dbh
  @name=name
end
end

server=Server.new("hostname","username","password","database_name")
server.databases.each {|x| puts x.name}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.