Quickstart: Use Ruby to query an Azure SQL database

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:

Get SQL server connection information

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. Sign in to the Azure portal.

  2. 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.

Create code to query your SQL database

  1. In a text or code editor, create a new file named sqltest.rb.

  2. Add the following code. Substitute the values from your Azure SQL database for <server>, <database>, <username>, and <password>.

    Important

    The code in this example uses the sample AdventureWorksLT data, which you can choose as source when creating your database. If your database has different data, use tables from your own database in the SELECT query.

    require 'tiny_tds'
    server = '<server>.database.windows.net'
    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. Verify that the top 20 Category/Product rows from your database are returned.

Next steps