RE: How to store connection string in congif file

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Matt Berther (mberther_at_hotmail.com)
Date: 11/29/04


Date: Mon, 29 Nov 2004 08:22:27 -0800

Hello John,

Even better would be a class that wraps the ConfigurationSettings, so that
you arent relying on magic constants...

class MyConfiguration
{
    public static string ConnectionString { get { return ConfigurationSettings.AppSettings["ConnectionString"];
} }
}

then: SqlConnection conn = new SqlConnection(MyConfiguration.ConnectionString);

This way, errors are caught at compile time, rather than runtime. Also, if
you happen to change the name of the setting in the app.config, you can change
it in one spot, rather than having to do a global search/replace.

--
Matt Berther
http://www.mattberther.com
> Hi Perin,
> In web.config file, add the section below.
> <configuration>
> <appSettings>
> <add key="ConnectionString"
> value="server=localhost;database=testdb;uid=sa;password=secret;"
> />
> </appSettings>
> <system.web>
> <customErrors mode="Off"/>
> </system.web>
> </configuration>
> In  your code, access like this..
> 
> strConnection = ConfigurationSettings.AppSettings("ConnectionString")
> sqlConn = New SqlConnection(strConnection)
> sqlCmd = New SqlCommand("SELECT * FROM Customers", sqlConn)
> sqlConn.Open()
> Very simple..
> 
> Rgds,
> John Paul. A
> "Perin" wrote:
> 
>> Hi,
>> I am using SQL Server as a Database in my ASP.NET application. Can
>> anyone
>> tell me, how to store my connection string in web.config file and
>> access it
>> from my application.
>> It is very urgent please..
>> -- Perin
>>