In this article, I have listed C# code snippets of connectionstring for Microsoft Sql Express Database.
Microsoft Sql Express Database ConnectionString in C#:
ConnectionString provide the required information to the driver that tells where to find the default connection information. Optionally, you are allowed to specify attribute=value pairs in the connection string to override the default values stored in the data source.
1. .NET Data Provider – Standard Connection with default relative path
using System.Data.Odbc; using System.Data.SqlClient; var conn = new SqlConnection(); conn.ConnectionString = "Data Source=.\SQLExpress;" + "User Instance=true;" + "User Id=UserName;" + "Password=Secret;" + "AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();
2. .NET Data Provider – Trusted Connection with default relative path
using System.Data.Odbc; using System.Data.SqlClient; var conn = new SqlConnection(); conn.ConnectionString = "Data Source=.\SQLExpress;" + "User Instance=true;" + "Integrated Security=true;" + "AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();
4. .NET Data Provider – Standard Connection with custom relative path
using System.Data.OleDb; using System.Data.SqlClient; AppDomain.CurrentDomain.SetData("DataDirectory", "C:\MyPath\"); var conn = new SqlConnection(); conn.ConnectionString = "Data Source=.\SQLExpress;" + "User Instance=true;" + "User Id=UserName;" + "Password=Secret;" + "AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();
5. .NET Data Provider — Trusted Connection with custom relative path
using System.Data.OleDb; using System.Data.SqlClient; AppDomain.CurrentDomain.SetData("DataDirectory", "C:\MyPath\"); var conn = new SqlConnection(); conn.ConnectionString = "Data Source=.\SQLExpress;" + "User Instance=true;" + "Integrated Security=true;" + "AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();
6. NET Data Provider – Standard Connection with absolute path
using System.Data.OleDb; using System.Data.SqlClient; var conn = new SqlConnection(); conn.ConnectionString = "Data Source=.\SQLExpress;" + "User Instance=true;" + "User Id=UserName;" + "Password=Secret;" + "AttachDbFilename=C:\MyPath\DataBaseName.mdf;" conn.Open();
7. .NET Data Provider – Trusted Connection with absolute path
using System.Data.SqlClient; using System.Data.SqlClient; var conn = new SqlConnection(); conn.ConnectionString = "Data Source=.\SQLExpress;" + "User Instance=true;" + "Integrated Security=true;" + "AttachDbFilename=C:\MyPath\DataBaseName.mdf;" conn.Open();
– Article ends here –