Get the connection string from web.config and connect to SQL Server in ASP.NET
Every data-driven Web Forms page starts the same way: read the connection string from web.config, open a SqlConnection, run a command, close it. Doing these steps correctly once, in a helper, saves a lot of trouble later.
1. Store it in web.config
<configuration>
<connectionStrings>
<!-- Windows authentication: the IIS application pool identity logs in -->
<add name="Db" providerName="System.Data.SqlClient"
connectionString="Data Source=SQL01;Initial Catalog=Shop;Integrated Security=True;Application Name=ShopWeb" />
</connectionStrings>
</configuration>
Common variants of the connectionString value:
| Scenario | Example |
|---|---|
| SQL Server Express on the same machine | Data Source=.\SQLEXPRESS;Initial Catalog=Shop;Integrated Security=True |
| LocalDB (development) | Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Shop;Integrated Security=True |
| SQL Server login | Server=SQL01;Database=Shop;User ID=shop_web;Password=… |
| Azure SQL Database | Server=tcp:myserver.database.windows.net,1433;Database=Shop;User ID=…;Password=…;Encrypt=True |
With Windows authentication, grant the application pool's identity (for example IIS APPPOOL\Shop) a login and only the database permissions it needs. With a SQL login, protect the password: see appSettings vs connectionStrings for encrypting the section.
2. Read it once
using System.Configuration;
public static class Db
{
public static string ConnectionString { get; } =
ConfigurationManager.ConnectionStrings["Db"]?.ConnectionString
?? throw new ConfigurationErrorsException("Connection string 'Db' is missing from web.config.");
}
Failing early with a clear message beats a NullReferenceException deep in a page.
3. Open, use, dispose
using (var con = new SqlConnection(Db.ConnectionString))
using (var cmd = new SqlCommand("SELECT COUNT(*) FROM dbo.Products", con))
{
con.Open();
int count = (int)cmd.ExecuteScalar();
lblCount.Text = count.ToString();
}
Open late, close early: using returns the connection to the pool even if an exception is thrown. Creating a new SqlConnection per operation is cheap thanks to connection pooling; keeping one open in a static field or in session is a classic source of errors under load.
Errors you may see
| Message | Likely cause |
|---|---|
| A network-related or instance-specific error occurred… (error 26 or 40) | Wrong server or instance name, SQL Browser stopped, TCP/IP disabled, or a firewall in between. |
| Login failed for user 'IIS APPPOOL\Shop' | The pool identity has no login or no access to the database. |
| Cannot open database "Shop" requested by the login | The login exists but has no user in that database, or the name is wrong. |
| The certificate chain was issued by an authority that is not trusted | Encryption is on and the server's certificate is not trusted (common with Microsoft.Data.SqlClient 4+, where Encrypt defaults to true). Install a trusted certificate; use TrustServerCertificate=True only for development. |
| Timeout expired… all pooled connections were in use | Connections are not being closed. Look for missing using blocks. |
Next steps: running commands and keeping them safe with parameters.
Official documentation
- Microsoft Learn: Connection string syntax, Connection strings and configuration files
- Microsoft Learn: SQL Server connection pooling
- Microsoft Learn: Introduction to Microsoft.Data.SqlClient