2012-07-08 31 views
13

我目前正在考慮使用SQLite作爲我的C#項目的數據庫引擎,但我遇到了以下問題:我無法找到任何用於內存存儲的API。我想要實現的是以下幾點:作爲數據庫的內存流

程序啓動時,我想將db文件(從硬盤)加載到內存中。 在程序執行過程中,我想把這個內存流作爲一個真正的數據庫(讀,寫,插入,選擇等)。 關閉後將流保存到文件。

任何人都可以用正確的方式指出我的意思,或者建議另一個更適合此目的的數據庫引擎。

回答

31

您可以使用SQLite Online Backup API有能力將db文件複製到內存,內存到文件。 SQLite Online Backup API的本地支持存在於版本1.0.80.0(含SQLite 3.7.11)的System.Data.SQLite中。

這是簡單的例子,如何API可以在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();    
} 
+1

謝謝你,這個漂亮和乾淨的解決方案。 – Anonymous 2012-07-08 20:40:34

+8

有沒有辦法做同樣的事情來獲得字節[]而不接觸磁盤? – Gleno 2013-08-31 22:57:54

+3

警告:對內存數據庫*使用備份API將刪除[耐久性](http://en.wikipedia.org/wiki/Durability_(database_systems))保證*。 – user2864740 2014-09-15 19:51:09