sql >> Base de Datos >  >> RDS >> Mysql

Cargue una imagen en C # y luego inserte en la tabla MySQL

Voy a ofrecer dos soluciones. La primera solución es almacenar la imagen sin procesar en bytes en la base de datos directamente. La segunda solución es la que recomiendo personalmente, que es usar la ruta del archivo de imagen en la base de datos.

Aquí un extracto de un artículo lo que trae a colación algunos puntos excelentes sobre si hacer BLOB o no.

Así es como elegiría su archivo de imagen:

using (var openFileDialog = new OpenFileDialog())
{
   openFileDialog.Title = "Choose Image File";
   openFileDialog.InitialDirectory =
                Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
   openFileDialog.Filter = "Image Files (*.bmp, *.jpg)|*.bmp;*.jpg";
   openFileDialog.Multiselect = false;
   if (openFileDialog.ShowDialog() == DialogResult.OK)
   {
       pictureBox1.Image = new Bitmap(openFileDialog.FileName);
   }
   // store file path in some field or textbox...
   textBox1.Text = openFileDialog.FileName;
}

Solución 1:enfoque BLOB

// Write to database like this - image is LONGBLOB type
string sql = "INSERT INTO imagetable (image) VALUES (@file)";
// remember 'using' statements to efficiently release unmanaged resources
using (var conn = new MySqlConnection(cs))
{
    conn.Open();
    using (var cmd = new MySqlCommand(sql, conn))
    {
        // parameterize query to safeguard against sql injection attacks, etc. 
        cmd.Parameters.AddWithValue("@file", File.ReadAllBytes(textBox1.Text));
        cmd.ExecuteNonQuery();
    }
}

// read image from database like this
string sql = "SELECT image FROM imagetable WHERE ID = @ID";
using (var conn = new MySqlConnection(cs))
{
   conn.Open();
   using (var cmd = new MySqlCommand(sql, conn))
   {
      cmd.Parameters.AddWithValue("@ID", myInt);
      byte[] bytes = (byte[])cmd.ExecuteScalar();   
      using (var byteStream = new MemoryStream(bytes))
      {
         pictureBox1.Image = new Bitmap(byteStream);
      }
   }
}

Solución 2:almacenar la ruta del archivo en el sistema de archivos

// Some file movement to the desired project folder
string fileName = Path.GetFileName(this.textBox1.Text);
string projectFilePath = Path.Combine(projectDir, fileName);
File.Copy(this.textBox1.Text, projectFilePath);

// Write to database like this - imagepath is VARCHAR type
string sql = "INSERT INTO imagepathtable (imagepath) VALUES (@filepath)";
using (var conn = new MySqlConnection(cs))
{
    conn.Open();
    using (var cmd = new MySqlCommand(sql, conn))
    {
        cmd.Parameters.AddWithValue("@filepath", projectFilePath);
        cmd.ExecuteNonQuery();
    }
}

// read from database like this
string sql = "SELECT imagepath FROM imagepathtable WHERE ID = @ID";
using (var conn = new MySqlConnection(cs))
{
    conn.Open();
    using (var cmd = new MySqlCommand(sql, conn))
    {
        cmd.Parameters.AddWithValue("@ID", myInt);
        pictureBox1.Image = new Bitmap(cmd.ExecuteScalar().ToString());
    }
}