Friday, January 18, 2013

Storing the Connection String in web.config


Typically, all the database code in your application will use the same connection string. For that reason, it usually makes the most sense to store a connection string in a class member variable or, even better, a configuration file. You can also create a Connection object and supply the connection string in one step by using a dedicated constructor:

SqlConnection myConnection = new SqlConnection(connectionString);
// myConnection.ConnectionString is now set to connectionString.

You don’t need to hard-code a connection string. The <connectionStrings> section of the web.config file is a handy place to store your connection strings. Here’s an example:

<configuration>
<connectionStrings>
<add name="Pubs" connectionString=
"Data Source=localhost;Initial Catalog=Pubs;Integrated Security=SSPI"/>
</connectionStrings>
...
</configuration>

You can then retrieve your connection string by name. First, import the System.Web.Configuration  namespace. Then, you can use code like this: 

string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;

This approach helps to ensure all your web pages are using the same connection string. It also makes it easy for you to change the connection string for an application, without needing to edit the code in multiple pages. The examples in this chapter all store their connection strings in the web.config file in this way. 

No comments:
Write comments
Recommended Posts × +