using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using SQLite; using WindowsFormsApp1.server; namespace WindowsFormsApp1.db { public class SQLiteHelper where T : new() { private readonly string _databasePath = Path.Combine(Environment.CurrentDirectory, "db\\MES_PLC.db"); //private readonly string _databasePath = "C:\\Users\\bnala\\source\\repos\\WindowsFormsApp1\\WindowsFormsApp1\\db\\MES_PLC.db"; private readonly SQLiteConnection _connection; // SQLite连接对象 /// /// 构造函数 /// public SQLiteHelper() { // 创建SQLite连接对象并打开连接 _connection = new SQLiteConnection(_databasePath); _connection.CreateTable(); // 如果表不存在,则创建该表[不会创建重复的表] } /// /// 数据插入 /// /// 要插入的数据项 /// public BllResult Insert(T item) { if(_connection.Insert(item) > 0) { return BllResult.Sucess(); } else { return BllResult.Error(); } } /// /// 数据删除 /// /// 要删除的数据的主键ID /// public BllResult Delete(int id) { if (_connection.Delete(id) > 0) { return BllResult.Sucess(); } else { return BllResult.Error(); } } /// /// 数据更新 /// /// 要更新的数据项 /// public BllResult Update(T item) { if(_connection.Update(item) > 0) { return BllResult.Sucess(); } else { return BllResult.Error(); } } public BllResult UpdateAll(List item) { if (_connection.UpdateAll(item) == item.Count) { return BllResult.Sucess(); } else { return BllResult.Error(); } } /// /// 根据条件查询记录 /// /// 查询条件 /// public BllResult> Query(Expression> predExpr) { var result = _connection.Table().Where(predExpr).ToList(); if (result.Count > 0 ) { return BllResult>.Sucess(result); } else { return BllResult>.Error(); } } /// /// 查询所有数据 /// /// public BllResult> QueryAll() { var result = _connection.Table().ToList(); if (result.Count > 0) { return BllResult>.Sucess(result); } else if (result.Count == 0) { return BllResult>.Sucess(new List()); } else { return BllResult>.Error(); } } /// /// 根据条件查询单条记录 /// /// 查询条件 /// public BllResult QuerySingle(Expression> predExpr) { var result = _connection.Table().Where(predExpr).FirstOrDefault(); if (result != null) { return BllResult.Sucess(result); } else { return BllResult.Error(result); } } } }