1

Im using C# to insert an image to Mysql database. The length of byte array is 51115. However, When I checked in database, the length of the field IMage (Long Blob) is only 13 bytes. What wrong is it? Please help me!

private void saveBtn_Click(object sender, EventArgs e)
{
    try
    {
        Image img = imgBox.Image;
        byte[] arr;
        ImageConverter converter = new ImageConverter();
        arr = (byte[])converter.ConvertTo(img, typeof(byte[]));
        MessageBox.Show(arr.Length.ToString()); // 51115
        string connectionString = "server=localhost;user id=root;password=xrayadmin;database=xraydatabase";
        string query = "INSERT INTO imagedatabase(IDPatient,Image,DiagnosisDoctor,DiagnosisDate) VALUES('" + Convert.ToInt32(labPatID.Text) + "','" +
            arr + "','" + labDocUser.Text + "','" + DateTime.Now.ToString("dd / MM / yyyy") + "')";
        MySqlConnection MysqlConnection = new MySqlConnection(connectionString);
        MySqlCommand MysqlCmd = new MySqlCommand(query, MysqlConnection);
        MySqlDataReader DataReader;
        MysqlConnection.Open();
        DataReader = MysqlCmd.ExecuteReader();
        MessageBox.Show("Save Data");
        while (DataReader.Read())
        {

        }
        MysqlConnection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

}
CharithJ
  • 46,289
  • 20
  • 116
  • 131
Huu Tin
  • 57
  • 1
  • 1
  • 8

2 Answers2

2

I recomend you to use parameters. Like this

string query = @"INSERT INTO imagedatabase(IDPatient,Image,DiagnosisDoctor,DiagnosisDate) VALUES(@IDPatient,@Image,@DiagnosisDoctor,@DiagnosisDate)"
MysqlCmd.Parameters.AddWithValue("@Image", arr);
Gelion
  • 34
  • 1
  • 4
2

The array will not be processed correctly when using string concatenation.

You need to be using query parameters and passing the byte array to a parameter. The .net database functions will handle the binary data correctly for you. See Parameterized Query for MySQL with C# for an example.

A search of stack overflow or your favorite search engine will yield a number of results on the right parameter types for whichever data type you are working with.

As an aside, by using string concatenation to write your queries, you are creating a huge risk of SQL injection (and if this is medical data as your code indicates, the fines for compromise of such data in the US and many other companies are very expensive). It's a very, very bad habit that's best to break as soon as possible.