using SQLite;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Sln.Iot.Repository
{
///
/// SQLite同步方法帮助类
///
///
public class SQLiteHelper where T : new()
{
private static readonly Lazy> lazy = new Lazy>(() => new SQLiteHelper());
public static SQLiteHelper Instance
{
get
{
return lazy.Value;
}
}
private readonly string _databasePath = Path.Combine(Environment.CurrentDirectory, "DeltaDatabase.db");
private readonly SQLiteConnection _connection; // SQLite连接对象
///
/// 构造函数
///
public SQLiteHelper()
{
// 创建SQLite连接对象并打开连接
_connection = new SQLiteConnection(_databasePath);
_connection.CreateTable(); // 如果表不存在,则创建该表[不会创建重复的表]
}
///
/// 数据插入
///
/// 要插入的数据项
///
public int Insert(T item)
{
return _connection.Insert(item);
}
///
/// 批量数据插入
///
///
///
public int InsertRange(List items)
{
return _connection.InsertAll(items);
}
///
/// 数据删除
///
/// 要删除的数据的主键ID
///
public int Delete(string id)
{
return _connection.Delete(id);
}
///
/// 根据托盘码批量删除记录
///
///
///
public int DeleteTrayRange(string trayCode)
{
return _connection.Execute($"DELETE FROM {typeof(T).Name} WHERE TrayCode = '{trayCode}'");
}
///
/// sql直接执行
///
///
///
public int SqlExcute(string sql)
{
return _connection.Execute(sql);
}
///
/// 数据更新
///
/// 要更新的数据项
///
public int Update(T item)
{
return _connection.Update(item);
}
///
/// 根据条件查询记录
///
/// 查询条件
///
public List Query(Expression> predExpr)
{
return _connection.Table().Where(predExpr).ToList();
}
///
/// 查询所有数据
///
///
public List QueryAll()
{
return _connection.Table().ToList();
}
///
/// 根据条件查询单条记录
///
/// 查询条件
///
public T QuerySingle(Expression> predExpr)
{
return _connection.Table().Where(predExpr).FirstOrDefault();
}
///
/// 查询单条记录(第一条)
///
///
public T QuerySingle()
{
return _connection.Table().FirstOrDefault();
}
}
}