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

标签 c# mysql

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

但是转换并没有失败: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/34358528/

相关文章:

mysql - 请发表意见 - 将旧数据库从 CHAR(14) PK 切换为 INT

php - 将中值函数与排序和数组结合使用

c# - 如何将 DropDownList 中的项目设置为默认值?

等效 LINQ 查询的 C# 代码

C# int 到标志枚举

c# - 将 WPF 应用程序添加到 Windows 任务栏

MySql 选择动态行值作为列名

PHP - 将 PDO 与 IN 子句数组一起使用

C# 表达式树 - 动态值查找

mysql - 数据库分区说明