Connection Strings

Beginner 15 min read Lesson 1 of 5

A connection string tells your C# app how to find and authenticate to a SQL Server database.

Typical connection string (Windows Authentication)

Server=localhost\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;TrustServerCertificate=True;

SQL Authentication (username/password)

Server=localhost\SQLEXPRESS;Database=SchoolDB;User Id=myuser;Password=mypassword;TrustServerCertificate=True;

Storing it properly in appsettings.json

Never hard-code connection strings in your C# files. Put them here instead:

{
  "ConnectionStrings": {
    "SchoolDb": "Server=localhost\\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}

Reading it in C#

string? connectionString = builder.Configuration.GetConnectionString("SchoolDb");

We'll cover keeping passwords out of source control entirely (User Secrets, environment variables) in the Security module.

Key Takeaway

Connection strings tell your app how to find the database. Store them in appsettings.json, never hard-code them.

Test Your Knowledge - Take Quiz