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

如何在C#中序列化内存中的SQLite数据库?

在C#中序列化内存SQLite数据库到文件的方案

你不需要用JSON序列化整个数据库,System.Data.SQLite原生提供了数据库备份API,可以高效且完整地将内存中的数据库序列化(备份)为字节流,之后可直接写入文件。以下是修改后的代码:

using System.Data.SQLite;
using System.IO;

public byte[] SerializeDB(string sql)
{
    using (var sourceCon = new SQLiteConnection("Data Source=:memory:;Version=3;New=True;"))
    {
        sourceCon.Open();
        // 执行初始化SQL,构建内存数据库结构和数据
        using (SQLiteCommand cmd = new SQLiteCommand(sql, sourceCon))
        {
            cmd.ExecuteNonQuery();
        }

        // 创建内存流存储备份数据
        using (var backupStream = new MemoryStream())
        {
            // 打开指向内存流的SQLite连接作为备份目标
            using (var destCon = new SQLiteConnection($"Data Source=file::memory:?mode=memory&cache=shared;"))
            {
                destCon.Open();
                // 将源内存数据库备份到目标连接(关联内存流)
                sourceCon.BackupDatabase(destCon, "main", "main", -1, null, 0);
                
                // 将备份后的流内容转为字节数组
                destCon.Close();
                return backupStream.ToArray();
            }
        }
    }
}

关键说明:

  • 原生备份API:SQLiteConnection.BackupDatabase是官方提供的方法,能完整保留数据库的所有结构、数据类型(包括BLOB、日期、整数等),比JSON序列化更可靠高效。
  • 字节数组用途:获取到的字节数组可以直接通过File.WriteAllBytes("your-db.sqlite", serializedBytes)写入文件,后续可直接用SQLiteConnection打开该文件。
  • 替代方案(直接写文件):如果不需要先存为字节数组,也可以直接备份到文件连接,省去内存流步骤:
// 直接备份到文件
using (var destCon = new SQLiteConnection("Data Source=backup.sqlite;Version=3;"))
{
    destCon.Open();
    sourceCon.BackupDatabase(destCon, "main", "main", -1, null, 0);
}

为什么不推荐JSON序列化?

  • JSON无法完整映射SQLite的所有数据类型,会导致数据丢失或类型转换错误(比如BLOB数据无法直接转为JSON)。
  • 序列化整个数据库到JSON会产生大量冗余数据,性能和空间利用率远低于原生备份格式。

内容的提问来源于stack exchange,提问作者bmurf17

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:45:38