由于某种原因,当我尝试更新用户的图像时,我的代码失败。图像未正确保存。例如,38 kib 的图像在数据库中保存为 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/55953176/