Connect to Azure SQL Database
यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।
This page describes how consuming apps connect to an Azure SQL Database resource that’s already modeled in your AppHost. For the AppHost API surface — adding an Azure SQL server, databases, running as a local container, managed identity, and more — see Azure SQL Database Hosting integration.
When you reference an Azure SQL Database resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire SQL Server client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called database becomes DATABASE_URI.
Azure SQL server resource
Section titled “Azure SQL server resource”The Azure SQL server resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The fully qualified domain name of the Azure SQL Server |
Port | The SQL Server port (1433 for Azure) |
Uri | The connection URI, with the format mssql://{Host}:{Port} |
JdbcConnectionString | JDBC connection string, with the format jdbc:sqlserver://{Host}:{Port};encrypt=true;trustServerCertificate=false |
Example connection strings:
Uri: mssql://myserver.database.windows.net:1433JdbcConnectionString: jdbc:sqlserver://myserver.database.windows.net:1433;encrypt=true;trustServerCertificate=falseAzure SQL database resource
Section titled “Azure SQL database resource”The Azure SQL database resource inherits all properties from its parent server resource and adds:
| Property Name | Description |
|---|---|
DatabaseName | The name of the database |
Uri | The connection URI with the database name, with the format mssql://{Host}:{Port}/{DatabaseName} |
JdbcConnectionString | JDBC connection string with the database name, with the format jdbc:sqlserver://{Host}:{Port};database={DatabaseName};encrypt=true;trustServerCertificate=false |
Example connection strings:
Uri: mssql://myserver.database.windows.net:1433/mydbJdbcConnectionString: jdbc:sqlserver://myserver.database.windows.net:1433;database=mydb;encrypt=true;trustServerCertificate=falseConnect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure SQL database resource named database and references it from the consuming app.
For C# apps, the recommended approach is the Aspire SQL Server client integration. It registers a SqlConnection through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.Microsoft.Data.SqlClient NuGet package in the client-consuming project:
dotnet add package Aspire.Microsoft.Data.SqlClient#:package Aspire.Microsoft.Data.SqlClient@*<PackageReference Include="Aspire.Microsoft.Data.SqlClient" Version="*" />Add the SQL Server client
Section titled “Add the SQL Server client”In Program.cs, call AddSqlServerClient on your IHostApplicationBuilder to register a SqlConnection:
builder.AddSqlServerClient(connectionName: "database");Resolve the connection through dependency injection:
public class ExampleService(SqlConnection connection){ // Use connection...}Add keyed SQL Server clients
Section titled “Add keyed SQL Server clients”To register multiple SqlConnection instances with different connection names, use AddKeyedSqlServerClient:
builder.AddKeyedSqlServerClient(name: "primary-db");builder.AddKeyedSqlServerClient(name: "secondary-db");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("primary-db")] SqlConnection primaryConnection, [FromKeyedServices("secondary-db")] SqlConnection secondaryConnection){ // Use connections...}For more information on keyed services, see .NET dependency injection: Keyed services.
Configuration
Section titled “Configuration”The Aspire SQL Server client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddSqlServerClient:
builder.AddSqlServerClient("database");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "database": "Server=myserver.database.windows.net;Database=mydb;Authentication=Active Directory Default;Encrypt=True" }}For more information on connection string format, see SqlConnection.ConnectionString.
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads MicrosoftDataSqlClientSettings from appsettings.json (or any other configuration source) by using the Aspire:Microsoft:Data:SqlClient key:
{ "Aspire": { "Microsoft": { "Data": { "SqlClient": { "DisableHealthChecks": false, "DisableTracing": false, "DisableMetrics": false } } } }}Inline delegates. Pass an Action<MicrosoftDataSqlClientSettings> to configure settings inline, for example to disable health checks:
builder.AddSqlServerClient( "database", static settings => settings.DisableHealthChecks = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The SQL Server client integration adds:
- A health check that attempts to connect to the Azure SQL Database instance and execute a command.
- Integration with the
/healthHTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire SQL Server client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging: The SQL Server client integration currently doesn’t enable logging by default due to limitations of the SqlClient.
Tracing activities:
OpenTelemetry.Instrumentation.SqlClient
Metrics from Microsoft.Data.SqlClient.EventSource:
active-hard-connectionshard-connectshard-disconnectsactive-soft-connectssoft-connectssoft-disconnectsnumber-of-non-pooled-connectionsnumber-of-pooled-connectionsnumber-of-active-connection-pool-groupsnumber-of-inactive-connection-pool-groupsnumber-of-active-connection-poolsnumber-of-inactive-connection-poolsnumber-of-active-connectionsnumber-of-free-connectionsnumber-of-stasis-connectionsnumber-of-reclaimed-connections
Any of these telemetry features can be disabled through the configuration options above.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and open a connection using 📦 Microsoft.Data.SqlClient:
using Microsoft.Data.SqlClient;
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URI");
await using var connection = new SqlConnection(connectionString);await connection.OpenAsync();
// Use connection to query the database...Use the microsoft/go-mssqldb driver, Microsoft’s officially maintained Go driver for SQL Server and Azure SQL Database:
go get github.com/microsoft/go-mssqldbRead the injected environment variable and connect:
package main
import ( "context" "database/sql" "os"
_ "github.com/microsoft/go-mssqldb")
func main() { // Read the Aspire-injected connection URI connStr := os.Getenv("DATABASE_URI")
db, err := sql.Open("mssql", connStr) if err != nil { panic(err) } defer db.Close()
if err := db.PingContext(context.Background()); err != nil { panic(err) }}Install pyodbc and the Microsoft ODBC Driver 18 for SQL Server:
pip install pyodbcRead the injected environment variables and connect using Azure Active Directory Default authentication:
import osimport pyodbc
# Read Aspire-injected connection propertiessql_host = os.getenv("DATABASE_HOST")sql_port = os.getenv("DATABASE_PORT", "1433")sql_database = os.getenv("DATABASE_DATABASENAME")
connection_string = ( f"DRIVER={{ODBC Driver 18 for SQL Server}};" f"SERVER={sql_host},{sql_port};" f"DATABASE={sql_database};" "Authentication=ActiveDirectoryDefault;" "Encrypt=yes;")
conn = pyodbc.connect(connection_string)cursor = conn.cursor()
# Use cursor to query the database...Install the mssql npm package, the most popular SQL Server and Azure SQL client for Node.js:
npm install mssqlnpm install --save-dev @types/mssqlRead the injected environment variables and connect:
import sql from 'mssql';
// Read Aspire-injected connection propertiesconst config: sql.config = { server: process.env.DATABASE_HOST!, port: Number(process.env.DATABASE_PORT), database: process.env.DATABASE_DATABASENAME, authentication: { type: 'azure-active-directory-default', }, options: { encrypt: true, },};
const pool = await sql.connect(config);
// Use pool to query the database...Or use the connection URI directly:
import sql from 'mssql';
const pool = await sql.connect(process.env.DATABASE_URI!);