Azure SQL Database Docs

Home

Connect Your Application to Azure SQL Database

This tutorial guides you through creating an Azure SQL Database, configuring firewall rules, and connecting from a .NET Core application using Microsoft.Data.SqlClient.

Prerequisites

Step 1 – Create the Azure SQL Database

az group create --name MyResourceGroup --location eastus
az sql server create --name myazuresqlserver --resource-group MyResourceGroup \
    --location eastus --admin-user sqladmin --admin-password <YourStrongP@ssw0rd>
az sql db create --resource-group MyResourceGroup --server myazuresqlserver \
    --name SampleDB --service-objective S0

Step 2 – Configure Firewall Rules

az sql server firewall-rule create --resource-group MyResourceGroup \
    --server myazuresqlserver --name AllowMyIP --start-ip 0.0.0.0 --end-ip 255.255.255.255

Step 3 – Get the Connection String

Run the following command to retrieve the ADO.NET connection string:

az sql db show-connection-string --server myazuresqlserver \
    --name SampleDB --client ado.net

Step 4 – Create a .NET Console App

Open a terminal and run:

dotnet new console -o SqlConnectDemo
cd SqlConnectDemo
dotnet add package Microsoft.Data.SqlClient

Step 5 – Write Connection Code

Create Program.cs with the following content:

using System;
using Microsoft.Data.SqlClient;

var connectionString = "Server=tcp:myazuresqlserver.database.windows.net,1433;Initial Catalog=SampleDB;Persist Security Info=False;User ID=sqladmin;Password=<YourStrongP@ssw0rd>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

try
{
    using var conn = new SqlConnection(connectionString);
    conn.Open();
    Console.WriteLine("Connection successful!");

    string query = "SELECT TOP 5 name FROM sys.tables;";
    using var cmd = new SqlCommand(query, conn);
    using var reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine(reader.GetString(0));
    }
}
catch (Exception ex)
{
    Console.WriteLine($\"Error: {ex.Message}\");
}

Step 6 – Run the Application

dotnet run

You should see Connection successful! followed by the list of table names.

Next Steps