内存流为DB [英] Memory Stream as DB

查看:96
本文介绍了内存流为DB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



当我要加载数据库文件(从HDD)到内存中的程序开始。
在执行程序我想用这个内存流作为一个真正的DB(读取,写入,插入,选择等)。
交易完成后保存流的文件。



任何人都可以点我在正确的道路或者提出另一个数据库引擎,这将是更适合用于这一目的。


解决方案

您可以使用的SQLite在线有到DB文件复制到记忆能力备份API ,存储到文件。对于 SQLite的在线备份API
原生支持存在于System.Data.SQLite从1.0.80.0版本(带。SQLite的3.7.11)



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



<预类=郎-CS prettyprint-覆盖> SQLiteConnection源=新SQLiteConnection(数据源= C:\\test.db);
source.Open();使用(:记忆:数据源=SQLiteConnection目的地=新SQLiteConnection(
))


{
destination.Open();

//数据库文件复制到内存
source.BackupDatabase(目的地,主,主, - 1,NULL,0);
source.Close();

//插入,使用select ...
(SQLiteCommand命令=新SQLiteCommand())
{
command.CommandText =
INSERT INTO T1(X)VALUES('一些新的价值');;

command.Connection =目标;
command.ExecuteNonQuery();
}

源=新SQLiteConnection(数据源= C:\\test.db);
source.Open();

//节省内存数据库到文件
destination.BackupDatabase(资料来源,主,主, - 1,NULL,0);
source.Close();
}


I'm currently thinking of using SQLite as db engine for my C# project, but i ran into the following problem: i can't find any API for memory storage. What i want to achieve is the following:

Upon start of the program i want to load the db file (from HDD) into memory. During execution of the program i want to use this memory stream as a real db (read,write,insert,select etc). Upon closing save the stream to the file.

Can anyone point me in the right way or suggest another db engine that would be better suited for this purpose.

解决方案

You can use SQLite Online Backup API that has ability to copy db file to memory, memory to file. Native support for SQLite Online Backup API is present in System.Data.SQLite from version 1.0.80.0 (with SQLite 3.7.11).

This is simple example how API can be used in C#:

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

这篇关于内存流为DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆