为什么会出现此错误:ConnectionString属性尚未初始化 [英] Why am I getting this error: The ConnectionString property has not been initialized

查看:422
本文介绍了为什么会出现此错误:ConnectionString属性尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索并尝试了所有内容,但无法弄清楚.我正在尝试做一些简单的事情,但似乎我做错了什么.基本上,任何已经存款的用户都想返回true,否则,我想返回false.我想这应该很容易,但是我对此感到困惑.

I have searched and tried everything but can't figure this one out. I am trying to do something simple but it seems as though I am doing something wrong. Basically, any user that has made a deposit, I want to return true, if they have not, I want to return false. This should be easy I suppose but I am stumped on this.

这是错误:

ConnectionString属性尚未初始化.

The ConnectionString property has not been initialized.

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

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.

源错误:

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()+4879939System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection externalConnection)+20System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection externalConnection,DbConnectionFactory connectionFactory)+117System.Data.SqlClient.SqlConnection.Open()+122

[InvalidOperationException: The ConnectionString property has not been initialized.] 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;
}

对此将提供任何帮助/指导.

Any help / guidance on this would be much appreciated.

推荐答案

如果您的连接字符串在这样的配置中

If you have your connection strings in your configuration like this

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

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

Then you will need to use this method to access it System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString

还应该在using语句中包装数据访问权限,以免泄漏连接并淹没池.这是一个使用using语句的更新示例.

You should also wrap your data access in using statements so that you don't leak connections and flood the pool. Here's an updated example with using statements.

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;
        }
    }
}

这篇关于为什么会出现此错误:ConnectionString属性尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆