C#将图像保存为Mybql数据库为blob

时间:2015-12-18 15:05:49

标签: 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

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

1 个答案:

答案 0 :(得分:2)

替换此代码:

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的参数。

无论哪种方式希望这对你有帮助。