简体   繁体   中英

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!

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

You can try

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

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

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

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>

如果你得到“无法将类型'system.configuration.connectionstringsettings'隐式转换为'string'”,请执行以下操作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM