Skip to content

Latest commit

 

History

History
103 lines (76 loc) · 5.69 KB

connect-query-ruby.md

File metadata and controls

103 lines (76 loc) · 5.69 KB
title titleSuffix description author ms.author ms.reviewer ms.date ms.service ms.subservice ms.topic ms.custom ms.devlang monikerRange
Use Ruby with Azure SQL Database or SQL Managed Instance
Azure SQL Database & Azure SQL Managed Instance
This quickstart shows you how to use Ruby to create a program that connects to a database and queries it using Transact-SQL statements.
dzsquared
drskwier
wiassaf, mathoma, randolphwest
09/15/2023
sql-db-mi
connect
quickstart
sqldbrb=2
mode-other
kr2b-contr-experiment
ruby
=azuresql || =azuresql-db || =azuresql-mi

Quickstart: Use Ruby to query a database in Azure SQL Database or Azure SQL Managed Instance

[!INCLUDE appliesto-sqldb-sqlmi]

This quickstart demonstrates how to use Ruby to connect to a database and query data with Transact-SQL statements.

Prerequisites

To complete this quickstart, you need the following prerequisites:

Get server connection information

Get the information you need to connect to a database in Azure SQL Database. You'll need the fully qualified server name or host name, database name, and sign-in 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 database in Azure SQL Database or the fully qualified server name (or IP address) next to Host for an Azure SQL Managed Instance or SQL Server on Virtual Machines. To copy the server name or host name, hover over it and select the Copy icon.

Note

For connection information for SQL Server on Azure Virtual Machines, see Connect to a SQL Server instance.

Create code to query your database in Azure 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 database in Azure SQL Database for <server>, <database>, <username>, and <password>.

    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

    [!INCLUDE article-uses-adventureworks]

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