SQLSugar是一種流行的C# ORM數據庫訪問庫,它提供了高性能、可擴展的ORM解決方案,使開發人員能夠輕鬆地使用.NET平台訪問關係型數據庫。
一、快速入門
在使用SQLSugar之前,你需要了解幾個基本概念,包括:連接字符串
、實體類
和數據表
。下面是一個簡單的示例,演示了如何使用SQLSugar查詢一張表:
using SqlSugar;
using System.Collections.Generic;
public class Student
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
public class Program
{
static void Main(string[] args)
{
// 設置連接字符串
string connectionString = "server=localhost;database=testdb;uid=root;pwd=123456;charset=utf8;";
// 創建SqlSugar對象
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = connectionString,
DbType = DbType.MySql,
IsAutoCloseConnection = true
});
// 查詢表中的所有數據
List students = db.Queryable().ToList();
// 打印結果
foreach (Student student in students)
{
Console.WriteLine(student.Name);
}
}
}
在上述示例中,我們創建了一個Student
實體類,並使用SugarColumn
註解標註該實體類在數據庫表中對應的字段信息。然後通過SqlSugarClient
對象創建連接,並使用Queryable
方法進行數據查詢。
二、數據查詢
1. 查詢所有數據
要查詢表中的所有數據,可以使用Queryable
方法,並對結果使用ToList
方法返回一個列表:
List<Student> students = db.Queryable<Student>().ToList();
2. 條件查詢
條件查詢是SQLSugar最常用的功能之一。在查詢數據時,可以使用Where
方法添加查詢條件:
List<Student> students = db.Queryable<Student>().Where(s => s.Age > 18 && s.Gender == "女").ToList();
在上述示例中,我們通過Where
方法查詢年齡大於18歲且性別為女的學生。
三、數據更新
SQLSugar可以非常方便地執行數據更新操作。要更新一條數據,你首先需要根據條件查詢到該數據,然後通過賦值操作來更新對應的值:
Student student = db.Queryable<Student>().Where(s => s.Id == 1).First();
student.Age = 20;
student.Gender = "男";
db.Updateable(student).ExecuteCommand();
在上述示例中,我們首先根據條件查詢到ID為1的學生,然後更新其年齡和性別信息,並通過Updateable
方法和ExecuteCommand
方法執行更新操作。
四、數據刪除
刪除一條數據也非常簡單。要刪除一條數據,你需要知道該數據的ID,然後使用Deleteable
方法執行刪除操作:
db.Deleteable<Student>().Where(s => s.Id == 1).ExecuteCommand();
在上述示例中,我們執行了刪除ID為1的學生數據的操作。
五、總結
SQLSugar是一個功能強大、易於學習和使用的ORM數據庫訪問庫。它提供了高性能、可擴展的ORM解決方案,使開發人員能夠輕鬆地使用.NET平台訪問關係型數據庫。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/238015.html