分页查询
//分页查询
try
{
// 第1步:获取第1页,每页5条数据
int pageIndex = 3;
int pageSize = 5;
// 第2步:获取总记录数,计算总页数
long totalNumber = db.Queryable<User>().Count();
int totalPages = (int)Math.Ceiling(totalNumber / (double)pageSize);
// 第3步:查询指定页数的数据
List<User> list = db.Queryable<User>()
.OrderBy(u => u.Id, OrderByType.Asc)
.ToPageList(pageIndex, pageSize);
// 第4步:输出查询结果
Console.WriteLine($"总记录数:{totalNumber}");
Console.WriteLine($"总页数:{totalPages}");
Console.WriteLine($"第{pageIndex}页数据:");
foreach (var user in list)
{
Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Password: {user.Password}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
创建对象
static void Main(string[] args)
{
// 创建SqlSugarClient对象
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "Server=localhost;Port=3306;Database=sqlsugar;Uid=root;Pwd=hox666666;", // MySQL连接字符串
DbType = DbType.MySql, // 设置数据库类型为MySQL
IsAutoCloseConnection = true // 自动关闭连接
});
实体类
class User
{
[SugarColumn(IsPrimaryKey = true)]
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}