csharp 临时让出 sqlite 数据库
使用 .Dump
SQLite 提供了 .dump 命令,可以将整个数据库导出为 SQL 脚本。你可以通过执行此命令生成备份文件,然后传输该文件。
实现步骤
- 使用 SQLite 命令行工具或代码执行
.dump 命令。
- 将生成的 SQL 文件传输到前端。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| using (var connection = new SQLiteConnection("Data Source=path/to/your/database.db")) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = ".dump";
using (var reader = command.ExecuteReader()) using (var writer = new StreamWriter("backup.sql")) { while (reader.Read()) { writer.WriteLine(reader.GetString(0)); } } }
|
使用 VACUUM(推荐)
SQLite 3.27.0 及以上版本支持 VACUUM INTO 命令,可以将数据库备份到一个新的文件中。
实现步骤
- 执行
VACUUM INTO 命令,将数据库备份到新文件。
- 传输新文件。
1 2 3 4 5 6 7
| using (var connection = new SQLiteConnection("Data Source=path/to/your/database.db")) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = "VACUUM INTO 'path/to/backup.db'"; command.ExecuteNonQuery(); }
|
EF Core 版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| private async Task DownloadSql() { if (File.Exists("backup.db")) { File.Delete("backup.db"); } using (var db=new Models.ChargeDb()) { var connection = db.Database.GetDbConnection(); await connection.OpenAsync(); using var command = connection.CreateCommand(); command.CommandText = "VACUUM INTO 'backup.db';"; command.ExecuteNonQuery(); }
var fileStream = File.OpenRead("backup.db"); var fileName = $"charging_{DateTime.Now:yyyy-MM-dd}.db";
using var streamRef = new DotNetStreamReference(stream: fileStream);
await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef); }
|
使用 EF Core 迁移
1
| dotnet ef migrations script --output backup.sql
|