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

前端 未结 3 479
醉话见心
醉话见心 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

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

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-01 05:01

    This error occurs when ConnectionString is null. Handle null value to fix this issue.

    0 讨论(0)
  • 2021-01-01 05:06

    In web.config :

    <appSettings>
        <add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
    </appSettings>
    
    0 讨论(0)
提交回复
热议问题