为什么我收到此错误:ConnectionString属性尚未初始化

时间:2013-08-17 01:25:47

标签: c# asp.net methods runtime-error

我已经搜索并尝试了所有内容,但无法想出这一个。我想做一些简单的事情,但好像我做错了什么。基本上,任何已存款的用户,我想返回true,如果他们没有,我想返回false。我想这应该很容易,但我对此感到难过。

以下是错误:

ConnectionString属性尚未初始化。

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.InvalidOperationException:尚未初始化ConnectionString属性。

来源错误:

Line 59:         Cmd.Parameters.AddWithValue("@UserID", userId);
Line 60:         con.Open();
Line 61: 
Line 62:         result = (int)Cmd.ExecuteScalar();

以下是堆栈跟踪的顶部:

[InvalidOperationException:ConnectionString属性尚未初始化。]    System.Data.SqlClient.SqlConnection.PermissionDemand()+ 4879939    System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)+20    System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection,DbConnectionFactory connectionFactory)+117    System.Data.SqlClient.SqlConnection.Open()+122

以下是我返回true或false的方法:

public static bool HasDeposit(int userId)
{
    int result = 0;
    //since executeScalar is intended to retreive only a single value
    //from a query, we select the number of results instead of the email address
    //of each matching result.
    string queryTransaction = "SELECT COUNT(UserID) FROM Transaction WHERE TransactionTypeID = 6 AND UserID = @UserID";
    string constr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
    SqlConnection con = new SqlConnection(constr);

    SqlCommand Cmd = new SqlCommand(queryTransaction, con);

    Cmd.Parameters.AddWithValue("@UserID", userId);
    con.Open();

    result = (int)Cmd.ExecuteScalar();

    //returning a boolean comparator works like this :
    //will return true if the result is greater than zero, but false if it is not.
    con.Close();
    return result > 0;
}

非常感谢任何关于此的帮助/指导。

3 个答案:

答案 0 :(得分:10)

如果你的配置中有连接字符串,就像这样

<connectionStrings>
    <add name="ConnectionString" connectionString="data source=.;Initial Catalog=MyDatabase;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>

然后,您需要使用此方法来访问它System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString

您还应该在using语句中包装数据访问权限,这样就不会泄漏连接并使池泛滥。这是使用语句的更新示例。

public static bool HasDeposit(int userId)
{
    //since executeScalar is intended to retreive only a single value
    //from a query, we select the number of results instead of the email address
    //of each matching result.
    const string queryTransaction = "SELECT COUNT(UserID) FROM Transaction WHERE TransactionTypeID = 6 AND UserID = @UserID";

    var constr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    using (var con = new SqlConnection(constr))
    {
        using (var cmd = new SqlCommand(queryTransaction, con))
        {
            cmd.Parameters.AddWithValue("@UserID", userId);
            con.Open();

            var result = (int)cmd.ExecuteScalar();

            //returning a boolean comparator works like this :
            //will return true if the result is greater than zero, but false if it is not.
            return result > 0;
        }
    }
}

答案 1 :(得分:1)

在web.config中:

<appSettings>
    <add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
</appSettings>

答案 2 :(得分:0)

当ConnectionString为null时,会发生此错误。处理空值可解决此问题。