Dinakar Nethi

A .NET/SQL Server Blog

<January 2009>
SuMoTuWeThFrSa
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567


Navigation

About Me

Links

Subscriptions

Article Categories



Store database connection string in web.config file

web.config file is a part of every asp.net application and is a good place for storing information that may be needed over multiple web pages. It also saves you a lot of “maintenance nightmare” if you need to make any change in all of them. Storing the database connection string in the web.config is one such good example.

A part of the web.config file is shown below :

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

</appSettings>

....

The connection string should be stored in the <appSettings> tag.

heres the complete example :


<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="conn" value="Data Source=localhost;Integrated Security=SSPI; database=YourDB" />

</appSettings>


And we can access this connection string from the .aspx page from the key “conn” from the key-value pair. So in our .aspx page we would say..

Protected objCon As New SqlConnection(ConfigurationSettings.AppSettings("conn"))

Sub Someprocedure()

'...other code

Try

If objCon.State = 0 Then objCon.Open()

Catch ex as exception

Finally

objCon.Close()

End Try

End Sub

  • Do not forget to close the connection in the finally block.

posted on Thursday, April 29, 2004 11:09 AM by dinakar





Powered by Dot Net Junkies, by Telligent Systems