在web.config中连接到SQL Server数据库的连接字符串是什么?

时间:2017-10-18 08:04:04

标签: c# asp.net sql-server web-config

使用ASP.NET连接到SQL Server数据库的web.config中的连接字符串是什么?

enter image description here

2 个答案:

答案 0 :(得分:0)

演示

<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />

答案 1 :(得分:0)

您可以在节点<connectionStrings></<connectionStrings>>中找到它 例如:

<connectionStrings>
  <add 
    name="NorthwindConnectionString" 
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User 
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

如何在代码中阅读:

System.Configuration.Configuration rootWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
            System.Configuration.ConnectionStringSettings connString;
            if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
            {
                connString =
                    rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
                if (connString != null)
                    Console.WriteLine("Northwind connection string = \"{0}\"",
                        connString.ConnectionString);
                else
                    Console.WriteLine("No Northwind connection string");
            }
  

更新:您需要在DbContext中指定连接名称

public class YourDbContext : DbContext 
{ 
    public YourDbContext() 
        : base("YourConnectionName") 
    { 
    } 
}

您的网络配置:

   <connectionStrings>
      <add name="YourConnectionName"
        connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True"
        providerName="System.Data.SqlClient" />
    </connectionStrings>