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

标签 c# mysql

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

相关文章:

c# - 带日期时间的 Firebird 数据库查询

c# - 如何为组件/脚本创建泛型池系统?

mysql - rails 将 geoip 资源保存在同一个数据库或分离的数据库中哪个更好?

c# - 创建或获取特定的 SPTimeZone 实例

c# - .net 中的 [] 括号是什么?

mysql - 如何解决 Cannot delete or update a parent row : a foreign key constraint fails in Spring

php - SQL 从历史记录中返回第一个记录日期

sql - 使用SQL显示数据

php - MySql - 将 InnoDB 转换为数据库的 MyISAM 存储引擎

c# - 通过 BHO 从 Outlook 拖放到 Internet Explorer 在 x32/86 机器上不起作用