c#从mysql检索保存的图像时出现错误
本文关键字:错误 图像 mysql 检索 保存 | 更新日期: 2023-09-27 18:14:02
我已经在表中创建了图像列mediumblob
保存图像,我使用以下代码
byte[] ImageData;
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
ImageData = new byte[Convert.ToInt32(fs.Length)];
fs.Read(ImageData, 0, Convert.ToInt32(fs.Length));
fs.Close();
string qry = "Update admin_info set `img`='"+ ImageData + "' where id='AD001";
using (con = new MySqlConnection(DBConStr))
{
con.Open();
using (cmd = new MySqlCommand(qry, con))
{
cmd.ExecuteNonQuery();
}
}
MessageBox.Show(" Profile Picture Updated Successfully!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
,它是成功的,但我得到参数无效,而检索它到图片框使用下面的代码
using (MySqlConnection conn = new MySqlConnection("Server = localhost; Port = 3307; database = attendance; uid = root; pwd = MJN45720!"))
{
conn.Open();
string myQuery = "SELECT img FROM admin_info where id='AD001'";
using (MySqlCommand cmd = new MySqlCommand(myQuery, conn))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
byte[] x = (byte[])reader["img"];
MemoryStream ms = new MemoryStream(x);
pictureBox1.Image = new Bitmap(ms); //Parameter invalid in this line
}
}
}
搜索了许多论坛,厌倦了他们在每个帖子中的建议,但我无法解决…
您没有正确地将图像保存到DB。string qry = "Update admin_info set ``img``='"+ ImageData + "' where id='AD001";
线将导致qry = "Update admin_info set ``img``='System.Byte[]' where id='AD001
,因为你正在转换字节数组到字符串,这将导致类型名称。您必须将字节数组转换为十六进制字符串,这应该被SQL引擎接受。
byte[] ImageData;
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
using (con = new MySqlConnection(DBConStr))
{
con.Open();
using (cmd = new MySqlCommand(qry, con))
{
cmd.Parameters.Add("@pimage", MySqlDbType.Blob);
cmd.Parameters["@pimage"].Value = ImageData;
cmd.ExecuteNonQuery();
}
}
这解决了我的问题,我也能检索…感谢Honz指出将其转换为sting的实际问题:)