gpt4 book ai didi

C# 将图像作为 blob 保存到 MySql 数据库

转载 作者:行者123 更新时间:2023-11-29 16:03:32 24 4
gpt4 key购买 nike

由于某种原因,当我尝试更新用户的图像时,我的代码失败。图像未正确保存。例如,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()。

但是转换不会失败:enter image description here

但是在数据库中我看到了这个:enter image description here

有谁知道这里发生了什么吗?

最佳答案

替换此代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com