SQL Server connection string in code vs config fil

2019-08-19 03:08发布

I already have a connection string in my config file

<connectionStrings>
    <add
        name="ConnectionString"
        connectionString="Data Source=*;Initial Catalog=*;User ID=*;Password=*"
        providerName=".NET Framework Data Provider for SQL Server" />

Currently I am just adding another connection string in my .cs file:

SqlConnection myConnection =
    new SqlConnection("user id=*;password=*;server=localhost;");

I want to use config file string to connect to a database in the .cs file without adding another string. How can I do that?

using (SqlConnection cn =
    new SqlConnection(
        ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))

This was the code I found, is there any shorter way?

4条回答
Rolldiameter
2楼-- · 2019-08-19 03:20

Just use System.Configuration.ConfigurationManager.ConnectionStrings to get access to the connection string defined in your config file.

 var myconnectionString = System.Configuration.ConfigurationManager
      .ConnectionStrings["ConnectionString"].ConnectionString;
查看更多
唯我独甜
3楼-- · 2019-08-19 03:23

You can create a static helper class, named Config or something similar and give it a property ConnectionString, that will return the long "WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString" thing. That is the approach I usually go with in my projects and it's actually very easy to use.

public static class Config
{
   public static string ConnectionString
   {
      get
      {
         return WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
      }
   }
}

This approach is the most useful when more classes need to acccess the connection string and this way you have a centralized access to it and easy to change solution.

查看更多
老娘就宠你
4楼-- · 2019-08-19 03:28

Using ConnectionStrings property of System.Web.Configuration.WebConfigurationManager to get connection string in config file

查看更多
倾城 Initia
5楼-- · 2019-08-19 03:37

Not really, but you could wrap it in its own little helper function:

private static string GetConnectionString(string name)
{
    return WebConfigurationManager.ConnectionStrings[name].ConnectionString;
}

using (var cn = new SqlConnection(GetConnectionString("MyDbConn"))) { ... }
查看更多
登录 后发表回答