第一步:创建SqlSugarClient对象
第二步:创建实体类
数据库中user表:
①添加
//① 添加数据
var newUser = new User() { Id = 9, Name = "猕猴桃666", Password = "9999" };
int rowsAffected = db.Insertable(newUser).ExecuteCommand();
Console.WriteLine("添加成功,影响的行数:" + rowsAffected);
var users = db.Queryable<User>().ToList();
Console.WriteLine("查询到的数据:");
foreach (var user in users)
{
Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Password: {user.Password}");
}
②修改
//② 更新数据
var userUpdate = db.Queryable<User>().In(new[] { 0 }).Single(); //从数据库中查询主键为0的User对象,并将结果存储在userUpdate变量中
if (userUpdate != null)
{
Console.WriteLine("原始数据:");
Console.WriteLine($"Id: {userUpdate.Id}, Name: {userUpdate.Name}, Password: {userUpdate.Password}");
userUpdate.Name = "烤鸡";
userUpdate.Password = "0000";
var rowsAffected = db.Updateable(userUpdate).ExecuteCommand();
Console.WriteLine("更新成功,影响的行数:" + rowsAffected);
//查询更新后的数据
var updatedUser = db.Queryable<User>().In(new[] { 0 }).Single(); //从数据库中查询主键为0的User对象,并将结果存储在userUpdate变量中
Console.WriteLine("更新后的数据:");
Console.WriteLine($"Id: {updatedUser.Id}, Name: {updatedUser.Name}, Password: {updatedUser.Password}");
}
else
{
Console.WriteLine("未找到要更新的数据。");
}
③查询
//③ 查询数据
try
{
List<User> list = db.Queryable<User>().ToList();
var A = db.Queryable<User>().Where(it => it.Id >= 10).ToList(); //条件查询
var B = db.Queryable<User>().Where(it => it.Name.Contains("水")).ToList(); //模糊查询
var C = db.Queryable<User>().Where(it => it.Id > 3 && it.Name.Contains("菠萝")).ToList(); //多条件查询
foreach (var user in list)
{
Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Password: {user.Password}");
}
if (list.Count == 0)
{
throw new Exception("未找到数据");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
④删除
//④ 删除数据
var userToDelete = db.Queryable<User>().In(new[] { 9 }).Single();
if (userToDelete != null)
{
Console.WriteLine("将要删除的数据:");
Console.WriteLine($"Id: {userToDelete.Id}, Name: {userToDelete.Name}, Password: {userToDelete.Password}");
var rowsAffected = db.Deleteable(userToDelete).ExecuteCommand();
Console.WriteLine("删除成功,影响的行数:" + rowsAffected);
}
else
{
Console.WriteLine("未找到要删除的数据。");
}
}
查询所有内容结果: