Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use connectionstring from web.config in source code file

Tags:

c#

asp.net

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!

like image 430
Rob Avatar asked Mar 15 '11 19:03

Rob


People also ask

How do you read ConnectionString from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

Where do I put ConnectionString in web config?

config file in the Views folder.) Find the <connectionStrings> element: Add the following connection string to the <connectionStrings> element in the Web. config file.

What is ConnectionString in web config?

<connectionStrings> <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System. Data. SqlClient" />


1 Answers

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

like image 171
David Avatar answered Sep 23 '22 13:09

David