如何使用ADO.NET将SQLite内存数据库转储到文件中?

7

我正在使用System.Data.SQLite.dll来使用SQLite内存数据库。程序结束后,我想将内存数据库转储到.db3文件以供下次使用。如何在C#中实现这一点?


我想像这样编写代码: <code> 使用 (var conn = new SQLiteConnection("Data Source=:memory:") { conn.Open();// 进行插入、更新等操作... // 如何将数据转储到文件中? conn.Close();} </code> - xiagao1982
1个回答

8
据我所知,System.Data.SQLite.dll 中没有内置功能可以实现此操作。但是,在 SQLite 核心中维护的 sqlite3.exe 客户端中存在该功能。
以下是我使用 system.data.sqlite.dll 实现此操作的方法:
  1. Obtain SQL statements to create new database structure.

    select sql from sqlite_master where name not like 'sqlite_%';
    
  2. Obtain names of all user tables.

    select name 
    from sqlite_master 
    where type='table' and name not like 'sqlite_%';
    
  3. Create the on-disk database in some new SQLiteConnection.

  4. Execute all previously obtained SQL statements to create the database structure in the on-disk database.

  5. Close the separate connection to the on-disk database.

  6. Attach the on-disk database to the in-memory database.

    attach 'ondisk.db3' as 'ondisk';
    
  7. For each user table obtained earlier, copy the content from the in-memory to the on-disk database.

    insert into ondisk.TableX select * from main.TableX;
    insert into ondisk.TableY select * from main.TableY;
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接