Ich biete zwei Lösungen an. Die erste speichert die rohen Bildbytes direkt in der Datenbank. Die zweite – die ich persönlich empfehle – speichert stattdessen den Dateipfad zum Bild.
Hier ist ein Auszug aus einem Artikel, der einige ausgezeichnete Punkte dazu aufwirft, ob man einen BLOB verwenden sollte oder nicht.
So gehen Sie vor, um Ihre Bilddatei auszuwählen:
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; } Lösung 1: Der BLOB-Ansatz
// 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); } } } Lösung 2: Speichern des Dateipfads auf dem Dateisystem
// 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()); } } Beide verwenden parametrisierte Abfragen, was wichtig ist, um Ihren Code vor SQL-Injection sicher zu halten.