rahstame
rahstame

Reputation: 2178

Saving Byte[] Array to MYSQL

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.

Upvotes: 2

Views: 22230

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503439

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

Upvotes: 5

Related Questions