[C#] [WPF] SqlSugar的基本使用

关于SqlSugar

一个ORM, 可以用在c#程序里操作数据
🍰 官方文档入口

怎么用SqlSugar

连接数据库

日常操作, 连接字符串, 数据库类型, 其他配置

SqlSugarClient db = new SqlSugarClient(new ConnectionConfig
{
    ConnectionString = $"Server={ip};Uid={uid};Pwd={pwd};Database={database};Charset=utf8mb4",
    DbType = DbType.MySql,
    IsAutoCloseConnection = true,
    InitKeyType = InitKeyType.Attribute
});
db.Open();

必要时加上try/catch捕获异常, 判断连接是否成功

查询

🍪 查询, 有各种查询
查询所有

List<Student> list=db.Queryable<Student>().ToList()

计数

int count=db.Queryable<Student>().Count()

按条件查询

db.Queryable<Student>().Where(it=>it.Id==1).ToList()
//select * from Student where id=1

db.Queryable<Student>().Where(it=>it.Id>10 && it.Name=="a").ToList()
//select * from Student where id > 10 and name = 'a'

插入

🍭 各种插入操作
插入单条数据/多条数据(List)

// T entity
db.Insertable(entity).ExecuteCommand();
// List<T> entities
db.Insertable(entities).ExecuteCommand();

更新

🍬还有根据实体对象更新等等, 看官方文档
根据表达式更新数据, 就是可以转成sql表达式, 用在需要按照sql表达式来用的情况?

// SetColumns字段是可以叠加的, 有几个就更新几个
// 更新单个字段
var result = db.Updateable<Student>()
.SetColumns(it => it.Name == "jack")
.Where(it => it.Id == 1)
.ExecuteCommand();

// 更新Name, createTime两个字段
var result = db.Updateable<Student>()
          .SetColumns(it => new Student() { Name="Alice",CreateTime=DateTime.Now})
          .Where(it => it.Id >11)
          .ExecuteCommand();

// 现有字段值++
var result = db.Updateable<Student>()
          .SetColumns(it => it.Num== it.Num+1)
          .Where(it => it.Id == 1)
          .ExecuteCommand();

删除

🍫 看官方文档
根据sql表达式删除

db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();

根据某主键删除

// 无主键时, 指定一列作为主键
db.Deleteable<Order>().In(it=>it.Id,1).ExecuteCommand();
posted @ 2024-06-24 17:02  Akira300000  阅读(11)  评论(0编辑  收藏  举报