Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

foreach loop does not encode and insert all bitmaps into my sqlite DB

My code:

private void BTN_Save_Click(object sender, EventArgs e)
        {
            string DBpath = @"Data Source=.\StudentDB.db;Version=3;";
            Bitmap[] PictureBoxesBitmaps = { FirstPictureBitmap, SecondPictureBitmap, ThirdPictureBitmap };
            using SQLiteConnection connection = new(DBpath);
            using SQLiteCommand cmd = new(DBpath, connection);
            foreach (Bitmap bitmap in PictureBoxesBitmaps)
            {
                System.IO.MemoryStream ms = new();
                bitmap?.Save(ms, ImageFormat.Png);
          
                    byte[] BitmapByteArray = ms.ToArray();
                    var PictureBox64  = Convert.ToBase64String(BitmapByteArray);
                    cmd.CommandText = @"INSERT INTO PictureBoxes(Encoded) VALUES('" + PictureBox64 + "')";
             
            }
            connection.Open();
            cmd.ExecuteNonQuery();
            connection.Close();
}

Only the first bitmap is encoded and inserted into the database.

My intention is to encode all bitmaps present in the PictureBoxexBitmaps array then insert them into the database.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried putting connection.Open(); cmd.ExecuteNonQuery(); and connection.Close(); under the foreach loop but that only encoded and inserted the first bitmap three times.

>Solution :

The command is being run only once, To fix the issue you need to move the below line inside the loop.

connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

and as a suggestion use using with the SQLiteConnection and please use the parameterized query to avoid SQL injection.

Edit:

As @madreflection suggested you could only move the cmd.ExecuteNonQuery(); inside the loop to avoid opening/closing the connection again and again. Thank you

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading