朝夕最新教程 简单用例 分库分表 老张.net8实践 图灵工控
1、文档右边有个红色按钮,一般会用个会比较方便。
2、文档左边有搜索可以方便找需要的内容
我们可以通过SqlSugarClient 或者SqlSugarScope 来操作数据库 ,API都一样只是模式不同
(1) SqlSugarClient 原生模式访问数据库
(2) SqlSugarScope 单例模式访问数据库
SqlSugarClient | 高性能:用法和Dapper、Ado、EF一样 ,不能单例,每个上下文都要是新的对象拥有超高性能,使用不当出现偶发错误通过IOC或者db.CopyNew()创建新的对象避免同一个对象在多个上下文使用 ,禁止单例 线程问题详细说明 疑问:new对象为什么性能好,因为new的只是一个C#对象,没有100万以上并发纯C#对象不占一点内存和CPU,数据库操作底层有ado连接池管理,.net中的orm性能远超java |
SqlSugarScope | 性能中上:对新手友好能解决除异步外所有线程安全问题同时还能保证不错的性能,原理是通过AsyncLocal实现,特殊情况:Task.WhenAll 、Parallel、Job或者异步不写await , 需要db.CopyNew()保证线程安全 线程问题详细说明 只能单例,不能一直new该对象是不会清空的,一直new会有内存问题 |
SqlSugarClient 每次请求new一个新对象,db禁止跨上下文使用,IOC建议用Scope或者瞬发注入
using SqlSugar;
//创建数据库对象 (用法和EF Dappper一样通过new保证线程安全)
SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "datasource=demo.db",
DbType = DbType.Sqlite,
IsAutoCloseConnection = true
},
db => {
db.Aop.OnLogExecuting = (sql, pars) =>
{
//获取原生SQL推荐 5.1.4.63 性能OK
Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
//获取无参数化SQL 对性能有影响,特别大的SQL参数多的,调试使用
//Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
};
//注意多租户 有几个设置几个
//db.GetConnection(i).Aop
});
//建库
Db.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库
//建表(看文档迁移)
Db.CodeFirst.InitTables<Student>(); //所有库都支持
//查询表的所有
var list = Db.Queryable<Student>().ToList();
//插入
Db.Insertable(new Student() { SchoolId = 1, Name = "jack" }).ExecuteCommand();
//更新
Db.Updateable(new Student() { Id = 1, SchoolId = 2, Name = "jack2" }).ExecuteCommand();
//删除
Db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();
//实体与数据库结构一样
public class Student
{
//数据是自增需要加上IsIdentity
//数据库是主键需要加上IsPrimaryKey
//注意:要完全和数据库一致2个属性
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public int? SchoolId { get; set; }
public string? Name { get; set; }
}Scope我们需要用SqlSugarClient
//注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
services.AddHttpContextAccessor();
//注册SqlSugar用AddScoped
services.AddScoped<ISqlSugarClient>(s =>
{
//Scoped用SqlSugarClient
SqlSugarClient sqlSugar = new SqlSugarClient (new ConnectionConfig()
{
DbType = SqlSugar.DbType.Sqlite,
ConnectionString = "DataSource=sqlsugar-dev.db",
IsAutoCloseConnection = true,
},
db =>
{
//每次上下文都会执行
//获取IOC对象不要求在一个上下文
//var log=s.GetService<Log>()
//获取IOC对象要求在一个上下文
//var appServive = s.GetService<IHttpContextAccessor>();
//var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
db.Aop.OnLogExecuting = (sql, pars) =>
{
};
});
return sqlSugar;
});
//用接口接收
public class(ISqlSugarClient db)详情:https://www.donet5.com/Home/Doc?typeId=1224
SqlSugarScope 请使用单例模式,配置参数有2种周期
全局生效 和 当前上下文生效
1.new SqlSugarScop(config,db=>{ db.xxx=yyyy; }) 所有上下文都会生效。
2.不在事件中直接db.xxx=yyy; 这儿只是当前上下文生效,不会跨上下文共享。
using SqlSugar;
//建库
SqlSugarHelper.Db.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库
//建表 (看文档迁移)
SqlSugarHelper.Db.CodeFirst.InitTables<Student>(); //所有库都支持
//查询表的所有
var list = SqlSugarHelper.Db.Queryable<Student>().ToList();
//插入
SqlSugarHelper.Db.Insertable(new Student() { SchoolId = 1, Name = "jack" }).ExecuteCommand();
//更新
SqlSugarHelper.Db.Updateable(new Student() { Id = 1, SchoolId = 2, Name = "jack2" }).ExecuteCommand();
//删除
SqlSugarHelper.Db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();
public class SqlSugarHelper //不能是泛型类
{
//多库情况下使用说明:
//如果是固定多库可以传 new SqlSugarScope(List<ConnectionConfig>,db=>{}) 文档:多租户
//如果是不固定多库 可以看文档Saas分库
//用单例模式
public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = "datasource=demo.db",//连接符字串
DbType = DbType.Sqlite,//数据库类型
IsAutoCloseConnection = true //不设成true要手动close
},
db => {
//(A)全局生效配置点,一般AOP和程序启动的配置扔这里面 ,所有上下文生效
//调试SQL事件,可以删掉
db.Aop.OnLogExecuting = (sql, pars) =>
{
//获取原生SQL推荐 5.1.4.63 性能OK
Console.WriteLine(UtilMethods.GetNativeSql(sql,pars));
//获取无参数化SQL 对性能有影响,特别大的SQL参数多的,调试使用
//Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
};
//多个配置就写下面
//db.Ado.IsDisableMasterSlaveSeparation=true;
//注意多租户 有几个设置几个
//db.GetConnection(i).Aop
});
}
//实体与数据库结构一样
public class Student
{
//数据是自增需要加上IsIdentity
//数据库是主键需要加上IsPrimaryKey
//注意:要完全和数据库一致2个属性
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public int? SchoolId { get; set; }
public string? Name { get; set; }
}验证单例是否成功:
SqlSugarHelper.Db.HasCode();//只要看这个hascode在服务启动后都一个那么说明成功了 //IOC直接复制我的DEMO就不需要验证
AddSingleton 我们需要用SqlSugarScope单例对象
//注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
services.AddHttpContextAccessor();
//注册SqlSugar
services.AddSingleton<ISqlSugarClient>(s =>
{
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
DbType = SqlSugar.DbType.Sqlite,
ConnectionString = "DataSource=sqlsugar-dev.db",
IsAutoCloseConnection = true,
},
db =>
{
//每次上下文都会执行
//获取IOC对象不要求在一个上下文
//var log=s.GetService<Log>()
//获取IOC对象要求在一个上下文
//var appServive = s.GetService<IHttpContextAccessor>();
//var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
db.Aop.OnLogExecuting = (sql, pars) =>
{
};
});
return sqlSugar;
});
//用接口接收
public class(ISqlSugarClient db)详情:https://www.donet5.com/Home/Doc?typeId=1224
var db = new SqlSugarClient(new List<ConnectionConfig>()
{
new ConnectionConfig()
{
ConfigId="0",DbType=DbType.SqlServer,ConnectionString=..,IsAutoCloseConnection=true
},
new ConnectionConfig()
{
ConfigId="1",DbType=DbType.MySql,ConnectionString=..,IsAutoCloseConnection=true
}
});
var childA=db.GetConnection("A");
var childB=db.GetConnection("B");详细教程:https://www.donet5.com/Home/Doc?typeId=2246
SqlSugarClient是通过ConnectionConfig进行传参数详细参数如下
| 名称 | 描述 | 必填 |
|---|---|---|
| DbType | 数据库类型 | 是 |
| ConnectionString | 连接字符串 | 是 |
| IsAutoCloseConnection | 自动释放和关闭数据库连接,如果有事务事务结束时关闭,否则每次操作后关闭 | |
| ConfigureExternalServices | 一些扩展层务的集成 | |
| MoreSettings | ||
| SlaveConnectionConfigs | 主从设置 | |
| LanguageType | 提示错误可以设置语言 |
设置超时时间
//Sql超时 db.Ado.CommandTimeOut = 30;//单位秒 //db.Open 连接超时 //在连接池符串加上 Connection Timeout=10 ,默认是30秒,单位秒
返回true是数据库连接成功
db.Ado.IsValidConnection() //如果时间长,可以在连接字符串配置 连接超时时间 //上面写法如果写到事务中会影响事务 //事务中我会可以new一个新对象处理 db.CopyNew().Ado.IsValidConnection() // 数据库连接成功
SqlSugarClient Db= new SqlSugarClient(new ConnectionConfig(){
ConnectionString = "连接符字串",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true},
db=>{
//5.1.3.24统一了语法和SqlSugarScope一样,老版本AOP可以写外面
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响
//获取原生SQL推荐 5.1.4.63 性能OK
Console.WriteLine(UtilMethods.GetNativeSql(sql,pars))
//获取无参数化SQL 对性能有影响,特别大的SQL参数多的,调试使用
Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
}
//注意多租户 有几个设置几个
//db.GetConnection(i).Aop
});
//老版本
//版本太老没有db=>{}委托写在下面一行就行了打印和上面有区别,需要一个一个设置
//注意:
//如果你用的 GetConnectionScope或者 GetConnectionScopeWithAttr AOP也应该用 GetConnectionScope
//如果你用的 GetConnection或者 GetConnectionWithAttr AOP也应该用 GetConnectionScope
SqlSugarClient Db= new SqlSugarClient(new ConnectionConfig(){
ConnectionString = "连接符字串",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true},
db=>{
//也可以这里面循环
db.GetConnection("1").Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine("执行1库"+sql);
};
db.GetConnection("0").Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine("执行0库"+sql);
};
});错误提示可以设置相应的语言
1.枚举说明
public enum LanguageType
{
Default=0, //中&英
Chinese=1, //处理过的异常尽量中文,未处理的还是英文
English=2 //全部英文
}2.用例
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
LanguageType=LanguageType.English,//只显示英文
IsAutoCloseConnection = true
});1.事务中是长连接
2.手动释放模式是长连接(不推荐需要手动释放)
3.自动释放中 不使用事务我们可以用OpenAlways实现长连接
//5.0.6.3
using (db.Ado.OpenAlways()) {
db.Queryable...
db.Insertable...
//比如当前会话生效的临时表就需要长连接,不然创建了访问不了
}新功能:5.0.8.1
推荐用默认的,这样多种数据库使用不报错,当然你也可以强制设置
db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings
{
DbMinDate = DateTime.MinValue//默认最小时间是 1900-01-01 00:00:00.000
};2016 © donet5.comApache Licence 2.0