由于某种原因,当我尝试为用户更新图像时,我的代码失败了。图像未正确保存。比如一张38kib的图片在数据库中保存为13字节。
这是我的代码:
public void UploadImage(Image img)
{
OpenConnection();
MySqlCommand command = new MySqlCommand("", conn);
command.CommandText = "UPDATE User SET UserImage = '@UserImage' WHERE UserID = '" + UserID.globalUserID + "';";
byte[] data = imageToByte(img);
MySqlParameter blob = new MySqlParameter("@UserImage", MySqlDbType.Blob, data.Length);
blob.Value = data;
command.Parameters.Add(blob);
command.ExecuteNonQuery();
CloseConnection();
}
public byte[] imageToByte(Image img)
{
using (var ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
}
OpenConnection 和 closeconnection 就是 conn.Open() 和 conn.Close()。
有人知道这里发生了什么吗?
最佳答案
替换这段代码:
OpenConnection();
MySqlCommand command = new MySqlCommand("", conn);
command.CommandText = "UPDATE User SET UserImage = '@UserImage' WHERE UserID = '" + UserID.globalUserID + "';";
byte[] data = imageToByte(img);
MySqlParameter blob = new MySqlParameter("@UserImage", MySqlDbType.Blob, data.Length);
blob.Value = data;
command.Parameters.Add(blob);
command.ExecuteNonQuery();
CloseConnection();
与
var userImage = imageToByte(img);
OpenConnection();
var command = new MySqlCommand("", conn);
command.CommandText = "UPDATE User SET UserImage = @userImage WHERE UserID = @userId;";
var paramUserImage = new MySqlParameter("@userImage", MySqlDbType.Blob, userImage.Length);
var paramUserId = new MySqlParameter("@userId", MySqlDbType.VarChar, 256);
paramUserImage.Value = userImage;
paramUserId.Value = UserID.globalUserID;
command.Parameters.Add(paramUserImage);
command.Parameters.Add(paramUserId);
command.ExecuteNonQuery();
CloseConnection();
您发送的 '@UserImage'
是一个 10 字节长的字符串,删除引号后它应该可以工作。
上面的代码还使用了两个变量的参数 which you should always do .
无论哪种方式,希望这对您有所帮助。
关于C# 将图像作为 blob 保存到 MySql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34358528/