我收到此错误 System.Data.SqlClient.SqlException (0x80131904): 操作数类型冲突: int 与图像不兼容

问题描述 投票:0回答:1

When I want to take a product image from the program and save it in the database, this happened

我尝试在保存到数据库后将图像保存在字节数组中, 但

imagebyteArray
返回
(int)

我逐行检查了所有代码,一切都很好,没有错误,但是当将照片保存到数据库中时,我定义为字节的变量返回值(int),并且照片显示为不存在转换字节。

这是我的代码:

Byte[] imagebyteArray;

// forimage
Image temp = new Bitmap(pictureBox1.Image);

MemoryStream ms = new MemoryStream();
temp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

imagebyteArray = ms.ToArray();

Hashtable ht = new Hashtable();
ht.Add("@id", id);
ht.Add("@Name", Textpname.Text);
ht.Add("@price", textprice.Text);
ht.Add("@cat", Convert.ToInt32(coCategory.SelectedValue));
ht.Add("@img", imagebyteArray);
        

这将打开对话框:

private void btnBrows_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        ofd.Filter = "image(.jpg, .png)|*.png;*jpg";

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            FilePath = ofd.FileName;
            PictureBox.Image = new Bitmap(FilePath);
        }
    }
}

这是在 SQL Server 中存储图像的代码:

string qry = "";

if (id == 0)//وارد کردن
{
    qry = "insert into Product values(@Name, @price, @img, @cat)";
}
else//بروز کردن
{
     qry = "Update Product set pName = @Name, pPrice = @price, CategoryID = @cat, pImage = @img where PID = @id";
}

要更新已存储在数据库中的产品:

private void ForUpdateLoade()
{
     string qry = @"select * from Product where PID = @id";

     using (SqlCommand cmd = new SqlCommand(qry, Mainclass.con))
     {
         SqlDataAdapter da = new SqlDataAdapter(cmd);
         DataTable dt = new DataTable();
         da.Fill(dt);

         if (dt.Rows.Count > 0)
         {
             Textpname.Text = dt.Rows[0]["pName"].ToString();
             textprice.Text = dt.Rows[0]["pPrice"].ToString();

             Byte[] imageArray = (byte[])(dt.Rows[0]["pImage"]);
             byte[] imagebyteArray = imageArray;
             pictureBox1.Image = Image.FromStream(new MemoryStream(imageArray));
         }
     }
 }
c# sql-server
1个回答
0
投票

在 INSERT 上指定目标列

qry = "insert into Product values(@Name, @price, @img, @cat)";

应该是

qry = "insert into Product(pName,pPrice,pImage,CategoryID) values(@Name, @price, @img, @cat)";
© www.soinside.com 2019 - 2024. All rights reserved.