Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

c# - Memory Stream as DB

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...