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)| Authentication | When | Connection string part |
|---|---|---|
| Windows (Integrated) | On-premises, domain/IIS app pool identity | Trusted_Connection=True |
| SQL authentication | Simple setups, non-Windows clients | User ID=...;Password=... |
| Microsoft Entra ID (Azure AD) — managed identity | Azure SQL from Azure services — no password | Authentication=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:
| Technology | How it connects | Minimal 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 Core | UseSqlServer(cs) | builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop"))) |
| Entity Framework 6 | DbContext("name=Shop") + web.config connection string | public ShopEntities() : base("name=ShopEntities") { } |
| Dapper | Extension methods on SqlConnection | conn.QueryAsync<Product>("SELECT * FROM dbo.Products") |
| ASP.NET Web Forms / MVC 5 | web.config <connectionStrings> + ConfigurationManager | ConfigurationManager.ConnectionStrings["Shop"].ConnectionString |
| ASP.NET Core | appsettings.json "ConnectionStrings" + GetConnectionString | see EF Core / Dapper rows |
| VB.NET | Same ADO.NET classes | Using cn As New SqlConnection(cs) : cn.Open() : End Using |
| SSIS | OLE DB / ADO.NET connection managers (MSOLEDBSQL provider) | Connection manager + project parameters for environments |
| SSRS | Shared data sources (stored credentials or Windows integrated) | Data source in Report Server |
| Node.js | mssql (tedious), Prisma, Sequelize | new sql.ConnectionPool({ server, database, user, password, options: { encrypt: true } }) |
| Next.js | Server Components / route handlers with mssql or Prisma — never client code | see the Next.js course |
| React / Angular / Vue / AngularJS | Through an HTTP API (ASP.NET Core / Node) — browsers never connect directly | fetch('/api/products') / HttpClient.get(...) / $http.get(...) |
| Python | pyodbc / mssql-python with ODBC Driver 18 | pyodbc.connect("DRIVER={ODBC Driver 18 for SQL Server};SERVER=...;DATABASE=Shop;Trusted_Connection=yes;Encrypt=yes") |
| Java | Microsoft JDBC driver | jdbc:sqlserver://host:1433;databaseName=Shop;encrypt=true |
| Power BI / Excel | Built-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:
| Error | Cause / 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 |