Why am I getting this error: The ConnectionString property has not been initialized

前端 未结 3 509
醉话见心
醉话见心 2021-01-01 04:27

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 u

3条回答
  •  春和景丽
    2021-01-01 05:01

    If you have your connection strings in your configuration like this

    
        
    
    

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

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

提交回复
热议问题