2014-02-26

SQL Server Connection Strings for ASP_NET Web Applications

http://blogs.msdn.com/b/aspnetue/archive/2012/08/14/sql-server-connection-strings-for-asp-net-web-applications.aspx


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;

[VB]
Dim connStr As String = 
WebConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString

Note that the namespace for this is System.Web.Configuration.WebConfigurationManager




No comments:

Post a Comment

Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/