开发者

SQL Server parameters array bol --> dal

开发者 https://www.devze.com 2022-12-23 15:43 出处:网络
The error is cannot convert object to sql parameter I\'m working with a bol->dal, building an ar开发者_开发百科ray of parameters to pass to the dal:

The error is cannot convert object to sql parameter

I'm working with a bol->dal, building an ar开发者_开发百科ray of parameters to pass to the dal:

bol:

SqlParameter[] sqlParams = new SqlParameter[]         
{   
    new SqlParameter("@p1", SqlDbType.VarChar, 30).Value = "val1",
    new SqlParameter("@p2", SqlDbType.VarChar, 30).Value = "val2"
};

dal:

    public static int ExecuteNonQuery(string sql, SqlParameter[] @params)
    {
        SqlConnection cnn = new SqlConnection(connectionstring);
        SqlCommand cmd = new SqlCommand(sql, cnn);
        for (int i = 0; i <= @params.Length - 1; i++)
        {
            cmd.Parameters.Add(@params[i]);
        }

        foreach (IDataParameter param in cmd.Parameters)
        {
            if (param.Value == null) param.Value = DBNull.Value;
        } 

        cnn.Open();
        int retval = cmd.ExecuteNonQuery();
        cnn.Close();
        return retval;
    }

I need help improving this, thanks--


You need to pass in the actual SqlParameter. Notice the object initializer of the Value:

var sqlParams = new SqlParameter[]
        {
            new SqlParameter("@p1", SqlDbType.VarChar, 30) {Value = "val1"},
            new SqlParameter("@p2", SqlDbType.VarChar, 30) {Value = "val2"},
        };
0

精彩评论

暂无评论...
验证码 换一张
取 消