简体   繁体   中英

Putting a connection string in the web config

So I'm using C# and I've got the following SQL connection string:

private static string _conn = Properties.Settings.Default.dBizConnectionString;

And I'd like to know if and how I can put it in the web config and app config? Thanks for the help!

The short answer is yes, like so:

<connectionStrings>
    <add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Server=ServerName; Initial Catalog=InitialCatalog; User ID=User; Password=Password; MultipleActiveResultSets=True;" />
</connectionStrings>

There's a lot of information out there about connection strings. There are more options you can specify, they can be encrypted, etc. etc., but this will get you started.

Here's a blog post from Scott Forsyth explaining everything:

Using Connection Strings from web.config

Add it to the web config like this:

  <connectionStrings>
     <add name="myConnectionStringName" connectionString="Data Source=mySqlServerInstance;Initial Catalog=myCatalog;User ID=myUserId;Password=myPassword"/>
  </connectionStrings>

Add code to retrieve it:

private static string GetConnectionString()
{
    var config = WebConfigurationManager.OpenWebConfiguration("/myProject");
    var connections = config.ConnectionStrings;
    var settings = connections.ConnectionStrings["myConnectionStringname"];
    string connectionString = settings.ConnectionString;
    return 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