Rob
Rob

Reputation: 7216

Use connectionstring from web.config in source code file

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!

Upvotes: 28

Views: 85197

Answers (6)

David
David

Reputation: 73604

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

Upvotes: 48

user1431356
user1431356

Reputation: 854

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

string connectionString = ConfigurationManager.ConnectionStrings["MainConnectString"].ConnectionString;

Upvotes: 1

Bala R
Bala R

Reputation: 109027

You can try

var conString = System.Configuration.
                ConfigurationManager.ConnectionStrings["connectionStringName"];
string strConnString = conString.ConnectionString;
SqlConnection con = new SqlConnection(strConnString);

Upvotes: 7

OrahSoft
OrahSoft

Reputation: 803

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>

Upvotes: 1

user279521
user279521

Reputation: 4807

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

Upvotes: 2

RQDQ
RQDQ

Reputation: 15579

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"];

Upvotes: 5

Related Questions