安装
● Visual Studio PowerShell
Remove-Package Microsoft.Data.Sqlite
Install-Package Microsoft.Data.Sqlite.Core
Install-Package SQLitePCLRaw.bundle_e_sqlcipher
● 在 Nuget Package Manager 安装
选择 Microsoft.Data.Sqlite.Core 和 SQLitePCLRaw.bundle_e_sqlcipher
导入包
using Microsoft.Data.Sqlite;
using System;
连接已加密的数据库
public static void Main() {
var connectionString = new SqliteConnectionStringBuilder() {
Mode = SqliteOpenMode.ReadWrite,
Password = "123", // 数据库密码
DataSource = "resource/database.db", // 数据库文件路径
}.ToString();
SqliteConnection connection = new SqliteConnection(connectionString);
connection.Open();
Work(connection);
connection.Close();
}
查询示例
public static void Work(SqliteConnection connection) {
var command = connection.CreateCommand();
command.CommandText = @"select count(*) from t_user";
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
int n = reader.GetInt32(0);
Console.WriteLine($"t_user 一共有 {n} 行");
}
}
}
修改已加密的数据库密码
public static void Work(SqliteConnection connection) {
var command = connection.CreateCommand();
string newPassword = "12345";
command.CommandText = $"PRAGMA rekey = '${newPassword}'";
command.ExecuteNonQuery();
}
参考链接
https://docs.microsoft.com/en-us/dotnet/standard/data/sqlite/encryption?tabs=visual-studio
https://www.zetetic.net/sqlcipher/