Roadmap › SQL Server & T-SQL › Module: Connecting Applications to SQL Server
Lessons in this course (19)

19. Connection strings, authentication and connecting from every technology

Basic★ Must knowLesson 19 of 19

Anatomy of a SQL Server connection string:

text
Server=tcp:myserver.database.windows.net,1433;   ← host (or ".\SQLEXPRESS", "localhost", "(localdb)\MSSQLLocalDB"), port 1433
Database=Shop;                                    ← (= Initial Catalog)
User ID=shop_app;Password=***;                    ← SQL authentication   OR   Trusted_Connection=True / Integrated Security=SSPI (Windows auth)
Encrypt=True;TrustServerCertificate=False;        ← TLS (Encrypt=True is the default since Microsoft.Data.SqlClient 4.0)
Connection Timeout=30;                            ← seconds to wait for a connection
MultipleActiveResultSets=False;                   ← MARS
Application Name=Shop.Api;                        ← shows in sys.dm_exec_sessions — great for diagnostics
Max Pool Size=100;Min Pool Size=0                 ← connection pooling (on by default)
AuthenticationWhenConnection string part
Windows (Integrated)On-premises, domain/IIS app pool identityTrusted_Connection=True
SQL authenticationSimple setups, non-Windows clientsUser ID=...;Password=...
Microsoft Entra ID (Azure AD) — managed identityAzure SQL from Azure services — no passwordAuthentication=Active Directory Managed Identity (or Active Directory Default)

Where to keep it: appsettings.json / web.config for non-secret parts, secrets in User Secrets (dev), environment variables, Azure Key Vault or managed identity (production). Never in source control or front-end code.

Every technology at a glance:

TechnologyHow it connectsMinimal example
ADO.NET (.NET)Microsoft.Data.SqlClient (System.Data.SqlClient in old Framework apps)using var cn = new SqlConnection(cs); cn.Open(); new SqlCommand("SELECT ...", cn).ExecuteReader()
Entity Framework CoreUseSqlServer(cs)builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")))
Entity Framework 6DbContext("name=Shop") + web.config connection stringpublic ShopEntities() : base("name=ShopEntities") { }
DapperExtension methods on SqlConnectionconn.QueryAsync<Product>("SELECT * FROM dbo.Products")
ASP.NET Web Forms / MVC 5web.config <connectionStrings> + ConfigurationManagerConfigurationManager.ConnectionStrings["Shop"].ConnectionString
ASP.NET Coreappsettings.json "ConnectionStrings" + GetConnectionStringsee EF Core / Dapper rows
VB.NETSame ADO.NET classesUsing cn As New SqlConnection(cs) : cn.Open() : End Using
SSISOLE DB / ADO.NET connection managers (MSOLEDBSQL provider)Connection manager + project parameters for environments
SSRSShared data sources (stored credentials or Windows integrated)Data source in Report Server
Node.jsmssql (tedious), Prisma, Sequelizenew sql.ConnectionPool({ server, database, user, password, options: { encrypt: true } })
Next.jsServer Components / route handlers with mssql or Prisma — never client codesee the Next.js course
React / Angular / Vue / AngularJSThrough an HTTP API (ASP.NET Core / Node) — browsers never connect directlyfetch('/api/products') / HttpClient.get(...) / $http.get(...)
Pythonpyodbc / mssql-python with ODBC Driver 18pyodbc.connect("DRIVER={ODBC Driver 18 for SQL Server};SERVER=...;DATABASE=Shop;Trusted_Connection=yes;Encrypt=yes")
JavaMicrosoft JDBC driverjdbc:sqlserver://host:1433;databaseName=Shop;encrypt=true
Power BI / ExcelBuilt-in SQL Server connector (Import or DirectQuery)Server + database + credentials, on-premises data gateway for cloud refresh
csharp
// ADO.NET done right: async, parameterised, pooled, disposed
await using var conn = new SqlConnection(cs);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("SELECT Id, Name FROM dbo.Products WHERE CategoryId = @cat", conn);
cmd.Parameters.Add("@cat", SqlDbType.Int).Value = categoryId;
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct)) Console.WriteLine($"{reader.GetInt32(0)} {reader.GetString(1)}");

Common connection errors:

ErrorCause / fix
"A network-related or instance-specific error… (error: 26/40)"Wrong server/instance name, SQL Browser stopped (named instances), TCP/IP disabled in SQL Server Configuration Manager, firewall port 1433 closed
"Login failed for user" (18456)Wrong credentials, SQL authentication not enabled (mixed mode), login has no access to the database, IIS app pool identity has no login
"The certificate chain was issued by an authority that is not trusted"Encrypt=True with a self-signed server certificate — install a trusted certificate, or TrustServerCertificate=True for local development only
"Timeout expired… pool"Connection leaks (not disposed) or too many concurrent requests — using/await using, check pool size, find long queries
Azure SQL "Cannot open server… not allowed"Server firewall — add the client IP or use private endpoints / allow Azure services