2964349
2964349

Reputation: 165

ASP.NET web development with C# : centralize the connection string

I am new to asp.net and C#. I am using a connection string in each and every page to connect to database and get results (the connection string is shown in the below code). Is there any way I can make the connection string centralized? So that I don't have to call it in each and every page?

Can anyone help me to solve this problem? please..

con = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=ewadb;Integrated Security=SSPI");

//data = new SqlDataAdapter("SELECT * FROM deals", con);
//dset = new DataSet();
//data.Fill(dset, "deal");

Upvotes: 0

Views: 568

Answers (5)

Jhabar
Jhabar

Reputation: 129

You can do that like below:

Web.Config:

Get the connection string in code: sqlConnection con = new sqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("connect‌​ion"));

Upvotes: 0

RobH
RobH

Reputation: 3612

You can put the connection string in the web.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <connectionStrings>
    <add name="default" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=ewadb;Integrated Security=SSPI" />
 </connectionStrings>
</configuration>

You can then get the value with the ConfigurationManager class:

ConfigurationManager.ConnectionStrings["default"].ConnectionString;

Architecturally speaking, your pages shouldn't be handling data access directly.

See here: http://en.wikipedia.org/wiki/Multitier_architecture for overview of n-tier architecture.

Upvotes: 3

Girish Vadhel
Girish Vadhel

Reputation: 745

Place the connection string into configuration section of your web.config file.

<configuration>
 <connectionStrings>
    <add name="default" connectionString="your connection string" />
 </connectionStrings>
</configuration>

Use below code to access connection string in page.

System.Configuration.ConfigurationManager.
    ConnectionStrings["connectionStringName"].ConnectionString;

Upvotes: 0

Amila Thennakoon
Amila Thennakoon

Reputation: 417

1) Use web.config file for store your connection string as this

<appSettings>
    <add key="connString_MyDB" value="Server=localhost;Integrated Security=false;Database=WORLD;Asynchronous Processing=True;user=sa;password=123;"/>
</appSettings>

2) to retrieve the connection string call as this in your class

  Private connString As String = System.Configuration.ConfigurationManager.AppSettings.Get("connString_MyDB").ToString

Upvotes: 0

stevepkr84
stevepkr84

Reputation: 1657

You should place it in the web.config. This means you can change it easily and call it consistently from anywhere. Please see the following for an intro.

http://msdn.microsoft.com/en-us/library/ms178411.aspx

Also a simple explaination:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Upvotes: 2

Related Questions