gpt4 book ai didi

c# - 内存流作为数据库

转载 作者:IT王子 更新时间:2023-10-28 23:30:17 26 4
gpt4 key购买 nike

我目前正在考虑使用 SQLite 作为我的 C# 项目的数据库引擎,但我遇到了以下问题:我找不到任何用于内存存储的 API。我想要实现的目标如下:

在程序启动时,我想将 db 文件(从 HDD)加载到内存中。在程序执行期间,我想将此内存流用作真正的数据库(读取、写入、插入、选择等)。关闭后将流保存到文件中。

谁能指出我正确的方式或建议另一个更适合此目的的数据库引擎。

最佳答案

您可以使用 SQLite Online Backup API能够将数据库文件复制到内存,内存到文件。对 SQLite Online Backup API 的原生支持存在于版本 1.0.80.0(使用 SQLite 3.7.11)的 System.Data.SQLite 中。

这是如何在 C# 中使用 API 的简单示例:

SQLiteConnection source = new SQLiteConnection("Data Source=c:\\test.db");
source.Open();

using (SQLiteConnection destination = new SQLiteConnection(
"Data Source=:memory:"))
{
destination.Open();

// copy db file to memory
source.BackupDatabase(destination, "main", "main",-1, null, 0);
source.Close();

// insert, select ,...
using (SQLiteCommand command = new SQLiteCommand())
{
command.CommandText =
"INSERT INTO t1 (x) VALUES('some new value');";

command.Connection = destination;
command.ExecuteNonQuery();
}

source = new SQLiteConnection("Data Source=c:\\test.db");
source.Open();

// save memory db to file
destination.BackupDatabase(source, "main", "main",-1, null, 0);
source.Close();
}

关于c# - 内存流作为数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11383775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com