SqlSugar操作Sqlite数据库
SqlSugar官网
.net core和.net5/.net6/.net7/.net8/.net9/.net10
安装SqlSugarCore。
net framework4.6+
安装SqlSugar。
以下代码都在一个SqlSugarMethod类中。
获得数据库对象:
这里要注意的是FilePath路径为生成程序的目录\bin\Debug\net8.0内,而不是代码目录内。
private string FilePath = Environment.CurrentDirectory + @"\SqlSugarDB\SugarSQL.db";private SqlSugarClient db = null;/// <summary>/// 获得数据库对象/// </summary>/// <returns></returns>public void GetSql(){db = new SqlSugarClient(new ConnectionConfig(){ConnectionString = $"Data Source={FilePath}", // SQLite 连接字符串DbType = DbType.Sqlite, // 指定数据库类型为 SQLiteIsAutoCloseConnection = true, // 自动关闭连接InitKeyType = InitKeyType.Attribute//从实体特性中读取主键自增列信息});}
创建数据库:
/// <summary>/// 创建数据库/// </summary>public bool CreateBase(){return db.DbMaintenance.CreateDatabase();}
创建数据表:
/// <summary>
/// 创建数据表
/// </summary>
public void CreateTable()
{//两种方法都能创建表//db.CodeFirst.InitTables(typeof(Student));db.CodeFirst.InitTables<Student>();
}//实体与数据库结构一样
public class Student
{//数据是自增需要加上IsIdentity//数据库是主键需要加上IsPrimaryKey//注意:要完全和数据库一致2个属性[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]public int Id { get; set; }public int? SchoolId { get; set; }public string? Name { get; set; }
}
查询一个表中全部数据:
/// <summary>
/// 查询一个表全部数据
/// </summary>
/// <returns></returns>
public List<Student> QueryAll()
{//查询表的所有return db.Queryable<Student>().ToList();
}
根据某些条件查询:
/// <summary>/// 查询/// </summary>/// <param name="a"></param>/// <param name="b"></param>/// <param name="c"></param>public void Query(out Student a, out List<Student> b, out List<Student> c){// 跟据主键查询:id为参数int id = 2;a = db.Queryable<Student>().InSingle(id);//根据某个数据查询:name为方法参数string name="Tom";b = db.Queryable<Student>().Where(s => s.Name == name).ToList();//模糊查询:方法参数key为关键字string key = "o";c = db.Queryable<Student>().Where(s => s.Name.Contains(key)).ToList();}
插入数据:
/// <summary>/// 插入数据/// </summary>public void InsertData(){var Tom = new Student(){Id = 2,SchoolId = 3,Name = "Tom"};db.Insertable(Tom).ExecuteCommand();}
更新数据:
/// <summary>/// 更新数据/// </summary>public void UpdateData(){var Tom = new Student(){Id = 2,SchoolId = 3505,Name = "Tom"};db.Updateable(Tom).ExecuteCommand();}
删除数据:
public void DeleteData()
{//根据主键db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();//根据主键数组db.Deleteable<Student>().In(new int[] { 1, 2 }).ExecuteCommand();
}