how to use web.config for sql connection string

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
 
G

George Durzi

<?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();
 
S

Steve C. Orr [MVP, MCSD]

<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.
 
B

Bill Dodd

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,900
Latest member
Nell636132

Latest Threads

Top