28

I know this might be a very basic question, but maybe thats why I'm having problems finding the answer. Right now I'm creating database connections in my source files by doing something like this:

SqlConnection con = new SqlConnection("Data Source=...Password=...);
SqlCommand cmd = new SqlCommand(String.Format("SELECT * FROM Table;"), con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();

But this means that if I choose to change databases it will be a major pain. Do you guys know how to use the connection string from a web.config file instead?

Thank you!

David
  • 72,686
  • 18
  • 132
  • 173
Rob
  • 7,028
  • 15
  • 63
  • 95
  • 3
    Just out of curiosity, are you closing / disposing your connections / commands / readers? If you're not using the 'using' keyword, start! – RQDQ Mar 15 '11 at 19:39

6 Answers6

48
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);

Make sure that your website has a reference to System.Configuration or it won't work.

The documentation can be found as How to: Read Connection Strings from the Web.config File, with code sample

chridam
  • 100,957
  • 23
  • 236
  • 235
David
  • 72,686
  • 18
  • 132
  • 173
7

You can try

var conString = System.Configuration.
                ConfigurationManager.ConnectionStrings["connectionStringName"];
string strConnString = conString.ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • 1
    +1: Note that the OP may have to manually add the System.Configuration reference to his project. – NotMe Mar 15 '11 at 19:36
5

In your app.config (or web.config):

<configuration>
       <connectionStrings>
           <add name="MainConnectString" connectionString="yourConnectionString" providerName="providerName" />
       </connectionStrings>
</configuration>

And in code:

string connectionString = ConfigurationManager.ConnectionStrings["MainConnectString"];
RQDQ
  • 15,461
  • 2
  • 32
  • 59
2

along with StackOverflowException's response, make sure to add using System.Configuration; to your code behind page

user279521
  • 4,779
  • 21
  • 78
  • 109
1

If you get "cannot implicitly convert type 'system.configuration.connectionstringsettings' to 'string'", do:

string connectionString = ConfigurationManager.ConnectionStrings["MainConnectString"].ConnectionString;
user1431356
  • 854
  • 7
  • 17
1

You can use EnterpriseLibrary.

using Microsoft.Practices.EnterpriseLibrary.Data;

Then you create a method to get connection string:

 public static string GetConnectionString()
    {
        Database YourData = DatabaseFactory.CreateDatabase("someconnectionname");
        return YourData .ConnectionString;
    }

In your web.config you will have following:

 <connectionStrings>   
   <add name="someconnectionname" connectionstring=..... />
 </connectionString>
OrahSoft
  • 783
  • 1
  • 5
  • 7