Storing and Retrieving Connection Strings in ASP.NET 2.0/3.5


A connection string specifies the database server, the database to be used, and various other settings such as authentication information depending on the data provider that is selected. The connection string may be hard-coded within your application or stored separately in the Web.config file. The recommended option is to store the connection string in Web.config, so that it is secure and also the connection settings such as database name can be modified any time without making changes to the individual Web pages.

In ASP.NET 2.0 and later, the connection string is stored in Web.config using the
<connectionStrings>element. One or more connection strings in the form of name-value pairs are stored between the <connectionStrings> and </connectionStrings> tags.

[Web.config file]

...

<
connectionStrings>
<
add name ="MyConnection"
connectionString ="server=Medusa;database=Products;
user id=sa; pwd=dollar"/>
</
connectionStrings>
...

The add child element of the <connectionStrings> element adds a connection string as a name/value pair to the collection of connection strings. If there is more than one connection string, the entire list of connection strings will be available as a collection.

Later, in the code-behind .cs file, the values stored in the
<connectionStrings> element in the Web.config file can be retrieved using the WebConfigurationManager class

The WebConfigurationManager class contains a public static property,
connectionStrings, which will return all the connection strings that have been stored in the Web.config file. You can iterate through the collection or extract the connection information of a particular connection string based on its name. Additionally, you can determine the number of connection strings stored in Web.config, add a connection, remove a connection, and retrieve a provider name.

The connection information retrieved using the WebConfigurationManager.ConnectionStrings property is typically stored into a string variable. Using this variable, a connection object such as is instantiated. The code below shows an example of this:

// Retrieving connection string from Web.config.
        String connString = WebConfigurationManager.ConnectionStrings["MyConnection"].ToString();
        SqlConnection conn = new SqlConnection(connString);
        conn.Open();

Summary: Thus, you have seen how to store database connection strings in the Web.config file in ASP.NET 2.0 and later, and retrieve it in the .cs file in order to create a connection object.

 

Up Next
    Ebook Download
    View all
    Learn
    View all