简体   繁体   中英

ExecuteNonQuery: Connection property has not been initialized. Sqlparameter array

I need help.. please tell me what wrong i did in this code, i messed up during passing parameter array to command. my store procedure is correct, connection string is also correct..

  internal string addmember(string name, string dob, string city, string state, string mobile, string email, string pass)
    {
        List<SqlParameter> param = new List<SqlParameter>();
        param.Add(new SqlParameter("@Mname",Convert.ToString(name)));
        param.Add(new SqlParameter("@Mdob",Convert.ToString(dob)));
        param.Add(new SqlParameter("@MemailId",Convert.ToString(email)));
        param.Add(new SqlParameter("@Mpassword", Convert.ToString(email)));
        param.Add(new SqlParameter("@McontactNo", Convert.ToString(mobile)));
        param.Add(new SqlParameter("@Mcity", Convert.ToString(city)));
        param.Add(new SqlParameter("@Mstate", Convert.ToString(state)));

        string result = Convert.ToString(executescaler(con, CommandType.StoredProcedure, "add_members", param.ToArray()));
            return result;
    }

    private string executescaler(string con, CommandType commandTyp, string procedure, SqlParameter[] sqlParameter)
    {
        string res;
        using (SqlConnection connection = new SqlConnection(con))
        {

            connection.Open();
            SqlCommand cmd = new SqlCommand(procedure, connection);
            cmd.CommandType = commandTyp;
            cmd.CommandText = procedure;
            cmd.Parameters.AddRange(sqlParameter);
            res=  cmd.ExecuteNonQuery().ToString();
        }
        return res;
    }

usually i use sqlhelper so never need to go through deep in ado.. but now im suffering because of that.. i dont get how to pass sqlparameter array to command

You didn't tell your SqlCommand that it should work with your SqlConnetion . Also, SqlCommand implements the IDisposable interface so you should be using it inside the using statement:

private string executescaler(string con, CommandType commandTyp, string procedure, SqlParameter[] sqlParameter)
{
    string res;
    using (var connection = new SqlConnection(con))
    {
        using(var cmd = new SqlCommand(procedure, con))
        {
            cmd.CommandType = commandTyp;
            cmd.Parameters.AddRange(sqlParameter);
            connection.Open();
            res = cmd.ExecuteNonQuery().ToString();
        }
    }
    return res;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM