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!
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
config file in the Views folder.) Find the <connectionStrings> element: Add the following connection string to the <connectionStrings> element in the Web. config file.
<connectionStrings> <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System. Data. SqlClient" />
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With