我正在尝试在内存中创建一个SQLite数据库,然后将其直接添加到我创建的zip文件中。到目前为止,我可以使用ZipArchive和ZipFile类创建zip文件。但是,我找不到将我在内存中创建的SQLite数据库添加到zip容器的方法。
以下是我在内存中创建数据库的代码:
private static void MemoryDB()
{
SQLiteConnection conn = new SQLiteConnection("Data Source = :memory:");
conn.Open();
String sql = "CREATE TABLE highscores (name VARCHAR(25), score INT)";
SQLiteCommand command = new SQLiteCommand(sql, conn);
command.ExecuteNonQuery();
// Insert Data
sql = "INSERT INTO highscores (name, score) VALUES ('Jennie', 98)";
command = new SQLiteCommand(sql, conn);
command.ExecuteNonQuery();
sql = "INSERT INTO highscores (name, score) VALUES ('Michael', 42)";
command = new SQLiteCommand(sql, conn);
command.ExecuteNonQuery();
sql = "INSERT INTO highscores (name, score) VALUES ('Jason', 76)";
command = new SQLiteCommand(sql, conn);
command.ExecuteNonQuery();
// Select Data
sql = "SELECT * FROM highscores ORDER BY score desc";
command = new SQLiteCommand(sql, conn);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]);
conn.Close();
}
我已经能够在磁盘上创建一个普通的数据库并使用ZipArchive.CreateEntryFromFile()方法将其添加到zip容器中,然后删除数据库,但是当你看到正在创建的数据库然后看起来非常糟糕除去。
必须有更好的方法吗?
谢谢,
答案 0 :(得分:3)
据我所知,您只能将内存数据库保存到磁盘(并将其加载回内存)using the SQLite Backup API。
在c#中,SQLiteConnection
有BackupDatabase
方法可以执行此操作。这仍然需要在磁盘上创建临时数据库文件(备份)。您可以这样做(假设您的内存连接名为source
):
var myBackupPath = @"c:\backups\backup.db";
using (var destination = new SQLiteConnection("Data Source=" + myBackupPath))
{
// saves from in-memory to the on-disk backup.
source.BackupDatabase(destination, "main", "main", -1, null, -1);
}
// Now you can zip the backup & delete it.