0

当我尝试在 ASP.NET (C#) 中建立与 SQL Server 数据库的连接时,出现以下错误:

ConnectionString 属性尚未初始化。

网页配置

<connectionStrings>
   <add name="ConnectionString" 
        connectionString="Data Source=SERVER\SQLEXPRESS;Initial Catalog=FIRE;Integrated Security=SSPI;User ID=firedba;Password=firedba;"/>

C# 代码

SqlConnection myConnection = new SqlConnection();
System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
System.Configuration.ConnectionStringSettings connString;

if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
        connString = rootWebConfig.ConnectionStrings.ConnectionStrings["ConnectionString"];

        if (connString != null)
            myConnection.Open();
}

我在 SQL Server(本地)中运行数据库。测试应用程序位于 Visual Studio 2008 中。

请问你能帮我吗?

4

2 回答 2

2

You need to set the ConnectionString in your SqlConnection Object.

Use :

if (connString != null){
        myConnection.ConnectionString=connString;
        myConnection.Open();
}

Or just create the SqlConnection object after get the Connection String:

            SqlConnection myConnection = new SqlConnection(connString);
            myConnection.Open();
于 2013-07-07T22:06:53.447 回答
1

You should inform the SqlConnection object which is the connection string to use when you try to open the link to the database

System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
    connString = rootWebConfig.ConnectionStrings.ConnectionStrings["ConnectionString"];

    if (connString != null)
    {
        // Create the connection, open, use and destroy releasing the resources used
        using(SqlConnection myConnection = new SqlConnection(connString))
        {
             myConnection.Open();

             .... other database code here
        } 

   }
}
于 2013-07-07T22:07:04.480 回答