You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历Bitmap数组时仅首个图片被插入SQLite数据库的问题求助

遍历Bitmap数组时仅首个图片被插入SQLite数据库的问题求助

大家好,我最近在做一个图片存入SQLite数据库的功能,遇到了一个奇怪的问题:当我遍历Bitmap数组,尝试把每个图片编码成Base64后插入数据库时,只有数组里的第一个Bitmap被成功插入了。

先贴一下我的代码:

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();
}

我原本的逻辑是,遍历数组里的每个Bitmap,逐个生成对应的INSERT语句,最后打开连接执行插入。但实际运行后,数据库里只有第一个Bitmap的记录。

后来我尝试把数据库连接的打开、执行插入和关闭操作都放到foreach循环里面,结果更奇怪了——第一个Bitmap被重复插入了三次,数组里的另外两个Bitmap还是没被插入进去。

我的目标很明确:把PictureBoxesBitmaps数组里的所有Bitmap分别编码后,各自作为一条独立的记录插入到SQLite的PictureBoxes表中。有没有朋友能帮我分析一下问题出在哪里,并且告诉我正确的写法应该是怎样的?


备注:内容来源于stack exchange,提问作者Ahmed Sherif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 07:43:12