Use Ruby to query an Azure SQL database
This quickstart demonstrates how to use Ruby to create a program to connect to an Azure SQL database and use Transact-SQL statements to query data.
To complete this quickstart, make sure you have the following prerequisites:
An Azure SQL database. You can use one of these techniques to create a database:
A server-level firewall rule for the public IP address of the computer you use for this quickstart.
You have installed Ruby and related software for your operating system:
SQL server connection information
Get the connection information needed to connect to the Azure SQL database. You will need the fully qualified server name, database name, and login information in the next procedures.
- Sign in to the Azure portal.
- Select SQL Databases from the left-hand menu, and click your database on the SQL databases page.
On the Overview page for your database, review the fully qualified server name as shown in the following image. You can hover over the server name to bring up the Click to copy option.
If you forget your server login information, navigate to the SQL Database server page to view the server admin name. If necessary, reset the password.
You must have a firewall rule in place for the public IP address of the computer on which you perform this tutorial. If you are on a different computer or have a different public IP address, create a server-level firewall rule using the Azure portal.
Insert code to query SQL database
In your favorite text editor, create a new file, sqltest.rb
Replace the contents with the following code and add the appropriate values for your server, database, user, and password.
require 'tiny_tds' server = 'your_server.database.windows.net' database = 'your_database' username = 'your_username' password = 'your_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
At the command prompt, run the following commands:
Verify that the top 20 rows are returned and then close the application window.