how to use web.config for sql connection string

  • Thread starter Thread starter steve
  • Start date Start date
S

steve

Hi,
I heard you could put your db connection string into the
web.config file to make it editable after you compile
and/or deploy.
I cant seem to find any info on this.. can any one help?
Sample code would be nice
Cheers
Steve
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="LDAPConnectString" value="LDAP://Domain.com/DC=Domain,DC=com" />
</appSettings>
</configuration>


in code.
using System.Configuration

string sLDAP =
ConfigurationSettings.AppSettings["LDAPConnectString"].ToString();
 
<configuration>
<appSettings>
<add key="DSN" value="Server=(local);Database=DBName;UID=sa;PWD="/>
<add key="OtherConnectionString"
value="Server=(local);Database=DBName2;UID=sa;PWD="/>
</appSettings>
</configuration>

This is a nice way to manage it. You can change the connection string
easily without rebuilding the app or restarting IIS or anything, and the
change goes into effect immediately.

Then in your code behinds you can get the connection string like this:
Dim sConn As String = ConfigurationSettings.AppSettings("DSN")

You'll want to put that line on every page that does data access. Open the
connection just before you need it and close it as soon as you are done with
it. Automatic connection pooling in ADO.NET makes this a very efficient
technique.
 
I put our connection strings in our machine.config file in
c:\(%windir%)\Microsoft.Net\Framework\(%Version%)\Config
Like this:
<appSettings>
<add key="connMainDB1" value="data source=ipaddy;initial
catalog=db1;persist security info=False;user
id=blah;password=blah;workstation id=webserver;packet size=4096"/>
<add key="connMainDB2" value="data source=ipaddy;initial
catalog=db2;persist security info=False;user
id=blah;password=blah;workstation id=webserver;packet size=4096"/>
</appSettings>

then, in your app you can read that out by:
Dim strConn As String =
System.Configuration.ConfigurationSettings.AppSettings("connMainDB1")



Of course, you can do the same thing in web.config.


Good Luck!

Bill
 
Back
Top