sqlparametercollection只接受非空的sqlparameter类型对象,不接受byte[]对象

本文关键字:对象 不接受 byte 类型 sqlparameter sqlparametercollection | 更新日期: 2023-09-27 18:10:44

运行时抛出异常的代码如下:

sqlparametercollection只接受非空sqlparameter类型的对象,不接受byte[]对象

我不明白这个错误是在这个方法中发生的:

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        // error handling removed
        cc.cn = new SqlConnection(cs.DBconn);
        cc.cn.Open();
        string cb = "insert into UserRegistration(U_ID,UserId,Name,Address,City,ContactNo,Email,Photo) VALUES (@d1,@d2,@d3,@d4,@d5,@d6,@d7,@d8)";
        cc.cmd = new SqlCommand(cb);
        cc.cmd.Connection = cc.cn;
        cc.cmd.Parameters.AddWithValue("@d1", txtId.Text);
        cc.cmd.Parameters.AddWithValue("@d2", txtUserId.Text);
        cc.cmd.Parameters.AddWithValue("@d3", txtUserName.Text);
        cc.cmd.Parameters.AddWithValue("@d4", txtAddress.Text);
        cc.cmd.Parameters.AddWithValue("@d5", txtCity.Text);
        cc.cmd.Parameters.AddWithValue("@d6", txtContactNo.Text);
        cc.cmd.Parameters.AddWithValue("@d7", txtEmailId);
        MemoryStream ms = new MemoryStream();
        Bitmap bmpImage = new Bitmap(Picture.Image);
        bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] data = ms.GetBuffer();
        SqlParameter p = new SqlParameter("@d8", SqlDbType.Image);
        p.Value = data;
        cc.cmd.Parameters.Add(p.Value);
        cc.cmd.ExecuteReader();
        cc.cn.Close();
        st1 = lblId.Text;
        st2 = "added the new User'" + txtUserName.Text + "' having User id '" +txtUserId.Text + "'";
        cf.LogFunc(st1, System.DateTime.Now, st2);
        btnSave.Enabled = false;
        MessageBox.Show("Successfully saved", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

我应该怎么做才能不出现这个错误?

sqlparametercollection只接受非空的sqlparameter类型对象,不接受byte[]对象

你有几个问题在代码blob:

 cc.cmd.Parameters.AddWithValue("@d7", txtEmailId.Text); // use the Text property!
 SqlParameter p = new SqlParameter("@d8", SqlDbType.Image);
 p.Value = data;
 cc.cmd.Parameters.Add(p); // add the SqlParameter instance, not the byte[] array

并不是严格需要的,但是当你不运行select语句时,你最好调用ExecuteNonQuery而不是ExecuteReader

 int rowsChanged = cc.cmd.ExecuteNonQuery();

ExecuteReader()仅用于SELECT查询。你需要使用ExecuteNonQuery()