ORM-SqlSugar使用
Nuget:
PM=> Install-Package SqlSugarCore

基本使用:
1.Mysql数据库:
2.创建控制台程序
// See https://aka.ms/new-console-template for more information using SqlSugar; SqlSugarClient db = new SqlSugarClient(new ConnectionConfig { ConnectionString = "Server=localhost;User ID=ADMIN;Password=ADMIN;port=3306;Database=TB666;CharSet=utf8;pooling=true;SslMode=None;", DbType = DbType.MySql, IsAutoCloseConnection = true }); Console.WriteLine("----------通过Mapping进行查询:Mapping------------------------"); //通过Mapping进行查询 var person = db.SqlQueryable<Person>("select ID, Name, Age, Address from person").ToList(); foreach (var item in person) { Console.WriteLine(item); } Console.WriteLine("----------直接执行SQL语句:DataTable------------------------"); //直接执行SQL语句: var dt=db.Ado.GetDataTable("select * from person"); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { Console.Write(dt.Columns[j].ColumnName+":"+dt.Rows[i][dt.Columns[j].ColumnName].ToString() +" "); } Console.WriteLine(); } public class Person { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } public override string ToString() { return $"ID:{ID} Name:{Name} Age:{Age} Address:{Address}"; } }
看看结果:
在Asp.Net Core中使用
public class DbContext { public static SqlSugarClient db = new SqlSugarClient(new ConnectionConfig { ConnectionString = "Server=localhost;User ID=Admin;Password=Admin;port=3306;Database=TB666;CharSet=utf8;pooling=true;SslMode=None;", DbType = DbType.MySql, IsAutoCloseConnection = true }); public static void InitDataBase() { //初始化数据库 //db.DbMaintenance.CreateDatabase("PERSON"); //string nspace = "Model.Entity"; //Type[] ass = Assembly.LoadFrom("bin/Debug/net6.0/Model.dll").GetTypes().Where(p => p.Namespace == nspace).ToArray(); //db.CodeFirst.SetStringDefaultLength(200).InitTables(ass); //模拟测试数据 List<Person> people = new List<Person> { new Person(){ID=1,Name="zhangsan",Age=1,Address="北极" }, new Person(){ID=2,Name="zhangsan2",Age=1,Address="北极" }, new Person(){ID=3,Name="zhangsan3",Age=1,Address="北极" }, new Person(){ID=4,Name="zhangsan4",Age=1,Address="北极" }, new Person(){ID=5,Name="zhangsan5",Age=1,Address="北极" }, new Person(){ID=6,Name="zhangsan6",Age=1,Address="北极" } }; //写入测试数据 db.Insertable(people).ExecuteCommand(); } } public class Person { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } public override string ToString() { return $"ID:{ID} Name:{Name} Age:{Age} Address:{Address}"; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探