Saving Byte[] Array to MYSQL

泄露秘密 提交于 2021-02-08 03:31:48

问题


Possibly Answered Here: storing image to byte[] into Mysql using asp.net and c#

using System.Drawing;
using System.Drawing.Imaging;

var imageBytes = imageToByteArray(pictureBox1.Image);     

var insert = new MySqlCommand("Insert INTO itemimage set imageName = '" + imageBytes + "'", _con);

insert.ExecuteNonQuery();   


public byte[] imageToByteArray(Image imageIn)
{
    var ms = new MemoryStream();
    imageIn.Save(ms, ImageFormat.Gif);
    return ms.ToArray();
}

Table: itemimage
2 | System.Byte[]  | 13byte    

3 | System.Byte[]  | 13byte

What is wrong with this code? thanks.


回答1:


What is wrong with this code?

You're using string concatenation to form the SQL. That's calling ToString on a byte array, which gives System.Byte[] as the result.

Instead, use a parameterized query, and set the parameter value to your byte array.

Something like this:

var data = ImageToByteArray(pictureBox.Image);
using (var cmd = new MySqlCommand("INSERT INTO itemimage SET imageName = @image",
                                  _con))
{
    cmd.Parameters.Add("@image", MySqlDbType.Blob).Value = data;
    cmd.ExecuteNonQuery();
}

Mind you, I'm a bit concerned about the column name here - is it really meant to be the name of an image (which is what the column name suggests) or the data in an image (which is what your code suggests)? Those are two very different things, and you should make it clear which is which.

You should always use parameterized queries:

  • They prevent SQL injection attacks
  • They reduce data conversion issues
  • They separate the code from the data more cleanly


来源:https://stackoverflow.com/questions/17185739/saving-byte-array-to-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!