using System; using System.Data.SQLite; namespace DownKyi.Core.Storage.Database { public class DbHelper { private readonly SQLiteConnection conn; /// /// 创建一个数据库 /// /// public DbHelper(string dbPath) { string connStr = $"Data Source={dbPath};Version=3;"; conn = new SQLiteConnection(connStr); } /// /// 创建一个带密码的数据库 /// /// /// public DbHelper(string dbPath, string secretKey) { string connStr = $"Data Source={dbPath};Version=3;"; conn = new SQLiteConnection(connStr); conn.SetPassword(secretKey); } /// /// 连接是否开启 /// /// public bool IsOpen() { return conn.State == System.Data.ConnectionState.Open; } /// /// 开启连接 /// public void Open() { if (!IsOpen()) { conn.Open(); } } /// /// 关闭数据库 /// public void Close() { if (IsOpen()) { conn.Close(); } } /// /// 执行一条SQL语句 /// /// public void ExecuteNonQuery(string sql) { lock (conn) { Open(); using (var tr = conn.BeginTransaction()) { using (var command = conn.CreateCommand()) { command.CommandText = sql; command.ExecuteNonQuery(); } tr.Commit(); } } } /// /// 执行一条SQL语句,并执行提供的操作,一般用于查询 /// /// /// public void ExecuteQuery(string sql, Action action) { lock (conn) { Open(); using (var command = conn.CreateCommand()) { command.CommandText = sql; var reader = command.ExecuteReader(); action(reader); } } } } }