【小白专用 已验证24.6.18】C# SqlSugar操作MySQL数据库实现增删改查-CSDN博客

通过NuGet包管理器搜索SqlSugarMySql还要安装MySql.Data、Newtonsoft.Json)包并安装

SqlSugarClient db = new SqlSugarClient(
    new ConnectionConfig()
    {
        ConnectionString = "server=.;uid=sa;pwd=@jhl85661501;database=SqlSugar4XTest",
        DbType = DbType.SqlServer,//设置数据库类型
        IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放
        InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
    });
     
     
//用来打印Sql方便你调试    
db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" + 
                db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };    
     
     
/*查询*/
var list = db.Queryable<StudentModel>().ToList();//查询所有
var getById = db.Queryable<StudentModel>().InSingle(1);//根据主键查询
var getByWhere = db.Queryable<StudentModel>().Where(it=>it.Id==1).ToList();//根据条件查询
var total = 0;
var getPage = db.Queryable<StudentModel>().Where(it => it.Id == 1).ToPageList(1,2,ref total);//根据分页查询
//多表查询用法 http://www.codeisbug.com/Doc/8/1124
 
/*插入*/
var data = new Student() { Name = "jack" };
db.Insertable(data).ExecuteCommand();
//更多插入用法 http://www.codeisbug.com/Doc/8/1130
 
/*更新*/
var data2 = new Student() { Id =1, Name = "jack" };
db.Updateable(data2).ExecuteCommand();
//更多更新用法 http://www.codeisbug.com/Doc/8/1129
 
/*删除*/
db.Deleteable<StudentModel>(1).ExecuteCommand();

实体类用法

//如果实体类名称和表名不一致可以加上SugarTable特性指定表名
[SugarTable("Student")]
public class StudentModel
{
    //指定主键和自增列,当然数据库中也要设置主键和自增列才会有效
    [SugarColumn(IsPrimaryKey=true,IsIdentity =true)]
    public int Id { get; set; }
    public string Name { get; set; }
}

根据实体类创建表

db.CodeFirst.SetStringDefaultLength(200/*设置varchar默认长度为200*/).InitTables(typeof(StudentModel));//执行完数据库就有这个表了
[SugarTable("T_DouPoClass")]
    public class StudentInfo
    {
        [SugarColumn(ColumnName = "F_Name",IsPrimaryKey =true)]
        public string Name { get; set; }
 
        [SugarColumn(ColumnName = "F_Gender")]
        public string Gender { get; set; }
        [SugarColumn(ColumnName = "F_Class")]
        public string Class { get; set; }
 
        [SugarColumn(ColumnName = "F_Grade")]
        public string Grade { get; set; }
    }

SqlSugar是通过Queryable、Updateable、Deleteable和Insertable实现的增删改查。

public static List<StudentInfo> Query()
        {
            var db = GetInstance();
            return db.Queryable<StudentInfo>().ToList();
        }

public static void Insert(StudentInfo student)
        {
            var db = GetInstance();
            db.Insertable<StudentInfo>(student).ExecuteCommand();
        }
public static bool Delete(StudentInfo student)
        {
            var db = GetInstance();
            db.Deleteable<StudentInfo>(student).ExecuteCommand();
            return true;
        }


public static bool Update(StudentInfo student)
        {
            var db = GetInstance();
            db.Updateable<StudentInfo>(new StudentInfo {Grade = student.Grade,Class= student.Class,Name= student.Name, Gender="异火"}).UpdateColumns(s => new {s.Gender}).WhereColumns(s => s.Name).ExecuteCommand();
            return true;
        }







    class Student
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }
        public string? Name { get; set; }
        public int Age { get; set; }
        public string? Home { get; set; }
    }
 
 


 Student student = new Student();
 student.Name = "小明";
 student.Age = 20;
 student.Home = "湖北武汉";
 db.Insertable(student).ExecuteCommand(); 



 List<Student> students = new List<Student>();
 students.Add(new Student() { Name = "小红", Age = 25, Home = "福建福州"});
 students.Add(new Student() { Name = "小钢", Age = 25, Home = "福建厦门" });
 students.Add(new Student() { Name = "小王", Age = 25, Home = "福建泉州" });
 students.Add(new Student() { Name = "小绿", Age = 25, Home = "江西南昌" });
 students.Add(new Student() { Name = "小吴", Age = 25, Home = "湖北襄阳" });

 db.Insertable(students).ExecuteCommand(); 

                        


 var list = db.Queryable<Student>().ToList();

 db.Queryable<Student>().Where(it => it.Age > 20).ToList();

 查单条
 var single = db.Queryable<Student>().Single(it => it.Id == 1);
 查字段,以Name为例
 var list3 = db.Queryable<Student>().Select(it => it.Name).ToList(); 

 以修改id=3的学生的home为“广东珠海”为例
 var single = db.Queryable<Student>().Single(it => it.Id == 3);
 single.Home = "广东珠海";
 db.Updateable(single).ExecuteCommand();



 条件删除,以删除id=1为例
 db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();

 根据主键数组删除,以删除id=2和3为例
 db.Deleteable<Student>().In(new int[] {2, 3}).ExecuteCommand();








SqlSugarClient db => GetInstance();
//执行sql语句,处理
//1.执行sql,转成list
List<teacher> list1 = db.Ado.SqlQuery<teacher>("select * from teacher where tsex=@tsex", new { tsex = "女" });
Console.WriteLine(list1.ToJsonString());
//2.转成dynamic
dynamic list2 = db.Ado.SqlQueryDynamic("select * from UserInfo");
Console.WriteLine(list2.Length);
//3.转成json数据
string list3 = db.Ado.SqlQueryJson("select * from UserInfo");
Console.WriteLine(list3);
//4.返回int
int count = db.Ado.SqlQuery<int>("select count(*) from UserInfo").FirstOrDefault();
Console.WriteLine(count);
 
//5.返回键值对类型
Dictionary<string, string> list4 = db.Ado.SqlQuery<KeyValuePair<string, string>>("select UserID,Name from UserInfo")
    .ToDictionary(q => q.Key, q => q.Value);
Console.WriteLine(list4.ToJsonString());
 
//6.返回List<string[]> 集合
List<string[]> list5 = db.Ado.SqlQuery<string[]>("select  * from teacher where tsex=@tsex", new { tsex = "女" });
Console.WriteLine(list5.ToJsonString());
//返回 DataTable
DataTable dataTable =  db.Ado.GetDataTable("select * from teacher where tsex=@tsex", new { tsex = "女" });



SqlSugarClient db => GetInstance();
//更方便的获取第一行第一列
string result1 = db.Ado.GetString(" select  name from UserInfo where UserID=@UserID", new { UserID = 1 });
Console.WriteLine(result1);
int count = db.Ado.GetInt("select count(*) from UserInfo");
Console.WriteLine(count);
double result2 = db.Ado.GetDouble("select avg(degree) from score where cno=@cno ", new System.Data.SqlClient.SqlParameter("@cno", "3-105"));
Console.WriteLine(result2);
 
decimal result3 = db.Ado.GetDecimal(" select avg(degree) from score");
Console.WriteLine(result3);

// 创建待插入数据
            var data = new bsae_info() { id = 2 ,name = "Sandy" , age = 13};
            // 插入数据
            db.Insertable(data).ExecuteCommand();
 
            // 执行插入操作
            db.Ado.ExecuteCommand("INSERT INTO bsae_info (id, name, age) VALUES (@id,@name,@age)",
                new {id = data.id, name = data.name, age=data.age });

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐