个人对数据库比较感兴趣
但是一直用的很少
最近又项目需要移植SqlServer的相关操作到某个系统
其实就是移植它的工具类咯
封装一些好用的工具来帮助操作SqlServer
当然我是不会花太多时间去研究原生的Sql代码的
太费时间 而且性能说不定还没别人写的号
最开始学java的时候ORM框架比较喜欢mybatis
那么.net一定也有它的ORM框架
网上找了一些下 决定使用SqlSugar 那么我们就可以开始啦
支持数据库:MySql、SqlServer、Sqlite、Oracle 、 postgresql、达梦、人大金仓
创建一个.net 5的控制台程序
引入nuget
就是它了
开干
在数据库中创建一个Student 表
插入三行数据
然后 开始引入最简单的示例
SqlSugarHelper.cs
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SqlSugarStudy
{
public class SqlSugarHelper
{
//查询所有
public List<Student> GetStudentList()
{
var db = GetInstance();//获取SqlSugarClient
var list = db.Queryable<Student>().ToList();//查询表的所有
return list;
}
//创建SqlSugarClient
private SqlSugarClient GetInstance()
{
//创建数据库对象
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "Data Source=192.168.0.15;Initial Catalog=Sugar;User ID=sa;Password=12345678;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",//连接符字串
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();
};
return db;
}
//实体与数据库结构一样
public class Student
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//主键并且自增 (string不能设置自增)
public int Id { get; set; }
public int? SchoolId { get; set; }
public string Name { get; set; }
public override string ToString()
{
return "Id--"+this.Id+"**SchoolId--"+this.SchoolId+"**Name--"+this.Name;
}
}
}
}
数据库的连接字符串请换成自己的
主程序
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using static SqlSugarStudy.SqlSugarHelper;
namespace SqlSugarStudy
{
class Program
{
static void Main(string[] args)
{
SqlSugarHelper sqlclient = new SqlSugarHelper();
List<Student> stus = sqlclient.GetStudentList();
foreach (var item in stus)
{
Console.WriteLine(item.ToString());
}
System.Console.ReadKey();
}
}
}
运行
成功查询
接下来可以开始进阶了