1. 在.net framework下设置Sqlite密码,访问数据,重设密码,删除密码。
using System;
using System.Data.SQLite;
namespace ConsoleApp1
{
class Program
{
private const string password = "abc.123";
static void Main(string[] args)
{
try
{
string dbFile = @"C:\repos\EFCoreDemos\EFCoreDemo1\Blogs.db";
// 1. Set password for your DB
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbFile+ ";Version=3;"))
{
conn.Open();
conn.ChangePassword(password);
}
// 2. Access data
using (var conn2 = new SQLiteConnection("Data Source=" + dbFile + ";Version=3;Password=" + password))
{
conn2.Open();
SQLiteCommand command = new SQLiteCommand("select * from blogs", conn2);
using (var reader = command.ExecuteReader())
{
while (reader.HasRows && reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.Write(reader[i] + ", ");
}
Console.WriteLine();
}
}
}
// 3. Clear db password
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbFile + ";Version=3;Password=" + password))
{
conn.Open();
conn.ChangePassword(string.Empty);
}
Console.ReadLine();
}
catch (Exception ex)
{
}
}
}
}
2. 在.net core目前不支持Sqlite密码相关的操作(甚至无法访问被密码加密的Sqlite数据库),但是可以使用以下方法Workaroud访问被密码加密的Sqlite数据库。请注意:这是在.net core下。
1) 设置一个扩展方法:
using System;
using System.Data.SQLite;
namespace EFCoreDemo1
{
public static class SQLiteConnectionExtension
{
public static void SetPassword(this SQLiteConnection connection, string password)
{
if (connection.State != System.Data.ConnectionState.Open)
throw new Exception("Open database first.");
var cmd = connection.CreateCommand();
cmd.CommandText = string.Format("PRAGMA key = '{0}'", password);
cmd.ExecuteNonQuery();
}
}
}
2)使用这个扩展方法:
using System;
using System.Data.SQLite;
namespace EFCoreDemo1
{
class Program
{
private const string password = @"abc.123";
static void Main(string[] args)
{
try
{
string dbFile = @"C:\repos\EFCoreDemos\EFCoreDemo1\Blogs.db";
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbFile))
{
conn.Open();
conn.SetPassword(password);
SQLiteCommand command = new SQLiteCommand("select * from blogs", conn);
using (var reader = command.ExecuteReader())
{
while (reader.HasRows && reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.Write(reader[i] + ", ");
}
Console.WriteLine();
}
}
}
}
catch (Exception ex)
{
;
}
}
}
}
参考:
1. https://stackoverflow.com/questions/39903863/password-protected-sqlite-with-entity-framework-core
2. https://stackoverflow.com/questions/1381264/password-protect-a-sqlite-db-is-it-possible