Amit
Amit

Reputation: 22086

Where to store Connection String in Web.Config?

We can store Connection String in Web.config file in two ways
One is

<connectionStrings>
    <clear/>
    <add name="LocalSqlServer"
          connectionString="Data Source=(local);Initial Catalog=aspnetdb;Integrated Security=True"
          providerName="System.Data.SqlClient" />
</connectionStrings>


Other One is

<appSettings>
     <add key="ConnectionString"
       value="server=localhost;database=Northwind;uid=sa;password=secret;" />
</appSettings>

Now I want to know
What is difference between these two approach?
Which one is better way?
What are their limitations?

UPDATE:Can you explain that <connectionString> has any significant advantage over <appSetting>?

Upvotes: 1

Views: 4961

Answers (6)

Besides the benefits mentioned in the other answers, connectionStrings elements have a providerName attribute that appSettings elements do not. This is particularly useful if your data source is not SQL Server.

Upvotes: 0

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9983

connection-string section is declare the connection for system.I mean that you application know that you string is connectionString. If you will use appSettings for application it is just any string value.

Upvotes: 1

Winger
Winger

Reputation: 676

If you add your connection strings to the appSettings section, you need to manually retrieve them using the ConfigurationManager.AppSettings.Get(key) method.

By adding your connection strings instead to the connectionStrings element, .NET can automatically find these by name when you create your connection object.

Upvotes: 2

System Down
System Down

Reputation: 6270

The first approach can be accessed directly by some data controls like SQLDataSource.

Upvotes: 6

Brian Lyttle
Brian Lyttle

Reputation: 14579

Using the connectionStrings element would be the most appropriate way to handle connection strings. The appSettings element is how connection strings used to be handled before .NET 2.0. You can use either approach but it is probably easier to work with multiple connection strings if you use the connectionString element. With multiple connection strings stored in appSettings you would have to parse each name (or value) to work out if it is a connection string before you could use it. This leads to maintenance issues. It's easier to just check if all of the connectionString items are present.

Upvotes: 5

Oded
Oded

Reputation: 499372

The connectionStrings section is dedicated to connection strings and was only introduced in .NET 2.0.

appSettings is more general and is to be used for other application settings.

You should use the connectionStrings section, as it can also be encrypted separately from any other settings.

Upvotes: 13

Related Questions