数据库
首页 > 数据库> > c#-将SQLite数据库直接添加到Zip文件

c#-将SQLite数据库直接添加到Zip文件

作者:互联网

我试图在内存中创建一个SQLite数据库,然后将其直接添加到我创建的zip文件中.到目前为止,我可以使用ZipArchiveZipFile类创建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容器中,然后删除该数据库,但是当您看到正在创建然后删除的数据库时,它看起来非常糟糕.

一定会有更好的办法?

谢谢,

解决方法:

据我所知,您只能将内存数据库保存到磁盘(并将其加载回内存)using the SQLite Backup API.

在c#中,SQLiteConnection具有可用于执行此操作的BackupDatabase方法.这仍然需要在磁盘上创建一个临时数据库文件(备份).您可以这样进行操作(假设您的内存连接名为源):

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.

标签:ziparchive,sqlite,zip,c,database
来源: https://codeday.me/bug/20191120/2043826.html