MSDN Documentation

Concepts: ADO.NET Connection Strings

Understanding ADO.NET Connection Strings

Connection strings are a fundamental part of using ADO.NET to connect to and interact with a data source. They provide the necessary information for the ADO.NET data provider to establish a connection.

What is a Connection String?

A connection string is a string that contains various parameters and their values, separated by semicolons, which are used to identify the data source and specify how to connect to it. These parameters can include information such as:

Common Connection String Parameters

While specific parameters vary by data provider, here are some common ones:

SQL Server Connection Strings

For SQL Server, common parameters include:

Example using SQL Server Authentication:

Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;

Example using Windows Authentication:

Server=myServerAddress;Database=myDataBase;Integrated Security=True;

Example connecting to a SQL Server Express instance:

Server=.\SQLEXPRESS;Database=myDataBase;User ID=myUsername;Password=myPassword;

OleDb Connection Strings (for various OLE DB data sources like Access)

For OLE DB providers, you often need to specify the provider:

Example for Microsoft Access:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\mydatabases\myDatabase.accdb;Persist Security Info=False;User ID=admin;Password=;

ODBC Connection Strings

For ODBC data sources, you'll typically specify the driver:

Example using an ODBC Driver:

Driver={ODBC Driver 17 for SQL Server};Server=myServerName;Database=myDatabaseName;Uid=myUsername;Pwd=myPassword;

Key Considerations

Building Connection Strings Programmatically

You can construct connection strings dynamically in your application code. For example, using C# with SqlConnectionStringBuilder:

// Using SqlConnectionStringBuilder in C#
            var builder = new SqlConnectionStringBuilder();
            builder.DataSource = "myServerAddress";
            builder.InitialCatalog = "myDataBase";
            builder.IntegratedSecurity = true;
            string connectionString = builder.ConnectionString;
            

This approach helps prevent syntax errors and makes your code more readable.

Note: The exact syntax and available parameters for connection strings can vary significantly between different data providers. Always consult the specific documentation for the provider you are using.