步驟 3︰使用 Ruby 連線到 SQL 的概念證明

這個範例只應被視為一個概念證明。 為了清楚起見,已將範例程式碼簡化,而其不一定代表 Microsoft 建議的最佳做法。

步驟 1:連線

TinyTDS::Client 函式可用來連接到 SQL Database。

    require 'tiny_tds'  
    client = TinyTds::Client.new username: 'yourusername@yourserver', password: 'yourpassword',  
    host: 'yourserver.database.windows.net', port: 1433,  
    database: 'AdventureWorks', azure:true  

步驟 2:執行查詢

複製以下程式碼並貼到空白檔案中。 稱它為 test.rb。 然後執行它,方法是從命令提示字元輸入下列命令:

    ruby test.rb  

在程式碼範例中, TinyTds::Result 函數可用來從針對 SQL Database 的查詢擷取結果集。 此函數會接受查詢,並傳回結果集。 結果集可使用 result.each do |row|重複列舉。

    require 'tiny_tds'    
    print 'test'       
    client = TinyTds::Client.new username: 'yourusername@yourserver', password: 'yourpassword',  
    host: 'yourserver.database.windows.net', port: 1433,  
    database: 'AdventureWorks', azure:true  
    results = client.execute("SELECT c.CustomerID, c.CompanyName,COUNT(soh.SalesOrderID) AS OrderCount FROM SalesLT.Customer AS c LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID GROUP BY c.CustomerID, c.CompanyName ORDER BY OrderCount DESC")  
    results.each do |row|  
    puts row  
    end  

步驟 3:插入資料列

在這個範例中,您將了解如何安全地執行 INSERT 陳述式、傳遞可保護您應用程式來防禦 SQL 插入值的參數。

若要搭配使用 TinyTDS 和 Azure,建議您執行多個 SET 陳述式來變更目前工作階段處理特定資訊的方式。 建議使用程式碼範例中所提供的 SET 陳述式。 例如,即使未明確陳述資料行的可為 null 狀態, SET ANSI_NULL_DFLT_ON 也可讓新建立的資料行允許 null 值。

為了與 Microsoft SQL Server 日期時間格式一致,請使用 strftime 函式來轉換成對應的日期時間格式。

    require 'tiny_tds'  
    client = TinyTds::Client.new username: 'yourusername@yourserver', password: 'yourpassword',  
    host: 'yourserver.database.windows.net', port: 1433,  
    database: 'AdventureWorks', azure:true  
    results = client.execute("SET ANSI_NULLS ON")  
    results = client.execute("SET CURSOR_CLOSE_ON_COMMIT OFF")  
    results = client.execute("SET ANSI_NULL_DFLT_ON ON")  
    results = client.execute("SET IMPLICIT_TRANSACTIONS OFF")  
    results = client.execute("SET ANSI_PADDING ON")  
    results = client.execute("SET QUOTED_IDENTIFIER ON")  
    results = client.execute("SET ANSI_WARNINGS ON")  
    results = client.execute("SET CONCAT_NULL_YIELDS_NULL ON")  
    require 'date'  
    t = Time.now  
    curr_date = t.strftime("%Y-%m-%d %H:%M:%S.%L")  
    results = client.execute("INSERT SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate)  
    OUTPUT INSERTED.ProductID VALUES ('SQL Server Express New', 'SQLEXPRESS New', 0, 0, '#{curr_date}' )")  
    results.each do |row|  
    puts row  
    end