快速入门:使用 Ruby 查询 Azure SQL 数据库Quickstart: Use Ruby to query an Azure SQL database

本快速入门演示了如何使用 Ruby 连接到 Azure SQL 数据库并使用 Transact-SQL 语句查询数据。This quickstart demonstrates how to use Ruby to connect to an Azure SQL database and query data with Transact-SQL statements.

先决条件Prerequisites

若要完成本快速入门,需要具备以下先决条件:To complete this quickstart, you need the following prerequisites:

获取 SQL Server 连接信息Get SQL server connection information

获取连接到 Azure SQL 数据库所需的连接信息。Get the connection information you need to connect to the Azure SQL database. 在后续过程中,将需要完全限定的服务器名称或主机名称、数据库名称和登录信息。You'll need the fully qualified server name or host name, database name, and login information for the upcoming procedures.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 导航到“SQL 数据库”或“SQL 托管实例”页。 Navigate to the SQL databases or SQL managed instances page.

  3. 在“概览”页中,查看单一数据库的“服务器名称”旁边的完全限定的服务器名称,或者托管实例的“主机”旁边的完全限定的服务器名称 。On the Overview page, review the fully qualified server name next to Server name for a single database or the fully qualified server name next to Host for a managed instance. 若要复制服务器名称或主机名称,请将鼠标悬停在其上方,然后选择“复制”图标 。To copy the server name or host name, hover over it and select the Copy icon.

创建用于查询 SQL 数据库的代码Create code to query your SQL database

  1. 在文本或代码编辑器中,创建新文件 sqltest.py 。In a text or code editor, create a new file named sqltest.rb.

  2. 添加以下代码。Add the following code. 将 Azure SQL 数据库中的值替换为<server><database>``<username><password>Substitute the values from your Azure SQL database for <server>, <database>, <username>, and <password>.

    Important

    本示例中的代码使用示例 AdventureWorksLT 数据,在创建数据库时可以选择该数据作为源。The code in this example uses the sample AdventureWorksLT data, which you can choose as source when creating your database. 如果数据库有不同数据,请在 SELECT 查询中使用自己数据库中的表。If your database has different data, use tables from your own database in the SELECT query.

    require 'tiny_tds'
    server = '<server>.database.chinacloudapi.cn'
    database = '<database>'
    username = '<username>'
    password = '<password>'
    client = TinyTds::Client.new username: username, password: password, 
        host: server, port: 1433, database: database, azure: true
    
    puts "Reading data from table"
    tsql = "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName
            FROM [SalesLT].[ProductCategory] pc
            JOIN [SalesLT].[Product] p
            ON pc.productcategoryid = p.productcategoryid"
    result = client.execute(tsql)
    result.each do |row|
        puts row
    end
    

运行代码Run the code

  1. 请在命令提示符处运行以下命令:At a command prompt, run the following command:

    ruby sqltest.rb
    
  2. 验证是否返回了数据库中的前 20 个类别/产品行。Verify that the top 20 Category/Product rows from your database are returned.

后续步骤Next steps