SQL Server Connection Strings for ASP.NET Web Applications
Please note that in C# backslash \ character has to be escaped using \\
So typically we have String connstr = "Data Source=.\\SQLEXPRESS;.....";
instead of just "Data Source=.\SQLEXPRESS;..."
A typical web.config file could have the following section which is placed directly under the root section.
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient">
<add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient">
</connectionStrings>
You can reference this directly from code using:
[C#]
string connStr = WebConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
string connStr = WebConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
[VB]
Dim connStr As String = WebConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString
Dim connStr As String = WebConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString
Note that the namespace for this is System.Web.Configuration.WebConfigurationManager
No comments:
Post a Comment