赞
踩
优点:
缺点:
创建对象:
public class Sugar { public static SqlSugarClient GetInstance() { SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = SqlSugar.DbType.MySql, ConnectionString = "server = 127.0.0.1; Database = sugarlearn; Uid = root; Pwd = root; AllowLoadLocalInfile = true;", InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true, LanguageType= LanguageType.Default }); //每次Sql执行前事件 db.Aop.OnLogExecuting = (sql, pars) => { var queryString = new KeyValuePair<string, SugarParameter[]>(sql, pars); if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT")) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"==============新增/修改操作=============="); } if (sql.StartsWith("DELETE")) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"==============删除操作=============="); } if (sql.StartsWith("SELECT")) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"==============查询操作=============="); } //ToSqlExplain 在标题6中有完整代码 Console.WriteLine(ToSqlExplain.GetSql(queryString));//输出sql Console.ForegroundColor = ConsoleColor.White; }; //SQL执行完 db.Aop.OnLogExecuted = (sql, pars) => { //执行时间超过1秒 if (db.Ado.SqlExecutionTime.TotalSeconds > 1) { //代码CS文件名 var fileName = db.Ado.SqlStackTrace.FirstFileName; //代码行数 var fileLine = db.Ado.SqlStackTrace.FirstLine; //方法名 var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName; //sql var exesql = sql; //参数 var sqlpars = pars; //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息 } }; //SQL报错 db.Aop.OnError = (exp) => { Console.WriteLine(exp.Sql); //exp.sql 这样可以拿到错误SQL }; return db; } }
调用对象:
static void Main(string[] args)
{
var db = Sugar.GetInstance();
bool connect = db.Ado.IsValidConnection(); //验证连接是否成功
List<Student> list = db.Queryable<Student>().ToList(); //查询Student表中所有数据
Console.ReadLine();
}
创建对象:
//Program.cs中添加如下代码 SugarIocServices.AddSqlSugar(new IocConfig() { //ConfigId="db01" 多租户用到 ConnectionString = "server=127.0.0.1;Database=ToDoDB;Uid=root;Pwd=root; AllowLoadLocalInfile=true;", DbType = IocDbType.MySql, IsAutoCloseConnection = true//自动释放 }); //多个库就传List<IocConfig> //配置参数 SugarIocServices.ConfigurationSugar(db => { db.Aop.OnLogExecuting = (sql, p) => { Console.WriteLine(sql); }; //设置更多连接参数 //db.CurrentConnectionConfig.XXXX=XXXX //db.CurrentConnectionConfig.MoreSettings=new ConnMoreSettings(){} //二级缓存设置 //db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices() //{ // DataInfoCacheService = myCache //配置我们创建的缓存类 //} //读写分离设置 //laveConnectionConfigs = new List<SlaveConnectionConfig>(){...} /*多租户注意*/ //单库是db.CurrentConnectionConfig //多租户需要db.GetConnection(configId).CurrentConnectionConfig });
调用对象:
public class TestController : ControllerBase
{
private static readonly SqlSugarClient db = DbScoped.Sugar;
public TestController()
{
}
public JsonResult Test()
{
var cs = db.Queryable<Student>().ToList();
return new JsonResult(cs);
}
}
注意:SqlSugarClient用 AddScoped 每次请求一个实例
创建对象:
public static class SqlsugarSetup { public static void AddSqlsugarSetup(this IServiceCollection services) { SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "server=127.0.0.1;Database=ToDoDB;Uid=root;Pwd=root; AllowLoadLocalInfile=true;", DbType = DbType.MySql, IsAutoCloseConnection = true, }); //每次Sql执行前事件 db.Aop.OnLogExecuting = (sql, pars) => { var queryString = new KeyValuePair<string, SugarParameter[]>(sql, pars); if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT")) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"==============新增/修改操作=============="); } if (sql.StartsWith("DELETE")) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"==============删除操作=============="); } if (sql.StartsWith("SELECT")) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"==============查询操作=============="); } //ToSqlExplain 在标题6中有完整代码 Console.WriteLine(ToSqlExplain.GetSql(queryString));//输出sql Console.ForegroundColor = ConsoleColor.White; }; //每次Sql执行后事件 db.Aop.OnLogExecuted = (sql, pars) => { //执行时间超过10秒 if (db.Ado.SqlExecutionTime.TotalSeconds > 10) { Console.WriteLine(sql); } }; //SQL报错 db.Aop.OnError = (exp) => { Console.WriteLine(exp.Sql); //exp.sql 这样可以拿到错误SQL }; services.AddScoped<ISqlSugarClient>(it => { return db; }); } }
Program.cs 依赖注入:
builder.Services.AddSqlsugarSetup();
调用对象:
private readonly ISqlSugarClient db;
public ToDoService(ISqlSugarClient _sqlSugarClient)
{
db = _sqlSugarClient;
}
public void Test()
{
var list = db.Queryable<Student>();
}
优点:
缺点:
创建对象:
public class Sugar { public static SqlSugarScope db = new SqlSugarScope(new ConnectionConfig() { ConnectionString = "server = 127.0.0.1; Database = sugarlearn; Uid = root; Pwd = root; AllowLoadLocalInfile = true;",//连接符字串 DbType = DbType.MySql,//数据库类型 IsAutoCloseConnection = true //不设成true要手动close }, db => { //调试SQL事件 db.Aop.OnLogExecuting = (sql, pars) => { var queryString = new KeyValuePair<string, SugarParameter[]>(sql, pars); if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT")) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"==============新增/修改操作=============="); } if (sql.StartsWith("DELETE")) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"==============删除操作=============="); } if (sql.StartsWith("SELECT")) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"==============查询操作=============="); } //ToSqlExplain 在标题6中有完整代码 Console.WriteLine(ToSqlExplain.GetSql(queryString));//输出sql Console.ForegroundColor = ConsoleColor.White; }; db.Aop.OnLogExecuted = (sql, pars) => { //执行时间超过1秒 if (db.Ado.SqlExecutionTime.TotalSeconds > 1) { //代码CS文件名 var fileName = db.Ado.SqlStackTrace.FirstFileName; //代码行数 var fileLine = db.Ado.SqlStackTrace.FirstLine; //方法名 var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName; //sql var exesql = sql; //参数 var sqlpars = pars; //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息 } }; }); }
调用方法一(类调用):
class Program
{
static void Main(string[] args)
{
bool connect = Sugar.db.Ado.IsValidConnection(); //验证连接是否成功
List<Student> list = Sugar.db.Queryable<Student>().ToList(); //查询Student表中所有数据
Console.ReadLine();
}
}
调用方法二(继承方式单例):
class Program : Sugar
{
static void Main(string[] args)
{
bool connect = db.Ado.IsValidConnection(); //验证连接是否成功
List<Student> list = db.Queryable<Student>().ToList(); //查询Student表中所有数据
Console.ReadLine();
}
}
创建对象:
//Program.cs中添加如下代码 SugarIocServices.AddSqlSugar(new IocConfig() { //ConfigId="db01" 多租户用到 ConnectionString = "server=127.0.0.1;Database=ToDoDB;Uid=root;Pwd=root; AllowLoadLocalInfile=true;", DbType = IocDbType.MySql, IsAutoCloseConnection = true//自动释放 }); //多个库就传List<IocConfig> //配置参数 SugarIocServices.ConfigurationSugar(db => { db.Aop.OnLogExecuting = (sql, p) => { Console.WriteLine(sql); }; //设置更多连接参数 //db.CurrentConnectionConfig.XXXX=XXXX //db.CurrentConnectionConfig.MoreSettings=new ConnMoreSettings(){} //二级缓存设置 //db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices() //{ // DataInfoCacheService = myCache //配置我们创建的缓存类 //} //读写分离设置 //laveConnectionConfigs = new List<SlaveConnectionConfig>(){...} /*多租户注意*/ //单库是db.CurrentConnectionConfig //多租户需要db.GetConnection(configId).CurrentConnectionConfig });
调用对象:
public class TestController : ControllerBase
{
private static readonly SqlSugarScope db = DbScoped.SugarScope;
public TestController()
{
}
public JsonResult Test()
{
var cs = db.Queryable<Student>().ToList();
return new JsonResult(cs);
}
}
注意:SqlSugarScope用单例AddSingleton 单例
创建对象:
public static class SqlsugarSetup { public static void AddSqlsugarSetup(this IServiceCollection services) { SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig() { DbType = SqlSugar.DbType.MySql, ConnectionString = "server = 127.0.0.1; Database = ToDoDB; Uid = root; Pwd = root; AllowLoadLocalInfile = true;", IsAutoCloseConnection = true, }, db => { //每次Sql执行前事件 db.Aop.OnLogExecuting = (sql, pars) => { var queryString = new KeyValuePair<string, SugarParameter[]>(sql, pars); if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT")) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"==============新增/修改操作=============="); } if (sql.StartsWith("DELETE")) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"==============删除操作=============="); } if (sql.StartsWith("SELECT")) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"==============查询操作=============="); } //ToSqlExplain 在标题6中有完整代码 Console.WriteLine(ToSqlExplain.GetSql(queryString));//输出sql Console.ForegroundColor = ConsoleColor.White; }; //SQL执行完 db.Aop.OnLogExecuted = (sql, pars) => { //执行时间超过1秒 if (db.Ado.SqlExecutionTime.TotalSeconds > 1) { //代码CS文件名 var fileName = db.Ado.SqlStackTrace.FirstFileName; //代码行数 var fileLine = db.Ado.SqlStackTrace.FirstLine; //方法名 var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName; //sql var exesql = sql; //参数 var sqlpars = pars; //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息 } }; //SQL报错 db.Aop.OnError = (exp) => { Console.WriteLine(exp.Sql); //exp.sql 这样可以拿到错误SQL }; }); services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton } }
Program.cs 依赖注入:
builder.Services.AddSqlsugarSetup();
调用对象:
private readonly ISqlSugarScope db;
public ToDoService(ISqlSugarClient _sqlSugarScope)
{
db = _sqlSugarScope;
}
public void Test()
{
var list = db.Queryable<Student>();
}
名称 | 描述 | 必填 |
---|---|---|
DbType | 数据库类型 | 是 |
ConnectionString | 连接字符串 | 是 |
IsAutoCloseConnection | 手动释放(长连接),自动释放(短连接) | 推荐自动释放 true |
ConfigureExternalServices | 一些扩展层务的集成 | |
MoreSettings | 更多设置 | 比如:配置最小时间 |
SlaveConnectionConfigs | 主从设置 | |
LanguageType | 错误提示设置语言 | 中文、英文、中英文混合 |
默认是30秒
db.Ado.CommandTimeOut = 30;//单位秒
//true:代表连接成功
bool connect = db.Ado.IsValidConnection();
Sql执行前的事件
在 db.Aop.OnLogExecuting 中拼接出完整Sql
//每次Sql执行前事件
db.Aop.OnLogExecuting = (sql, pars) =>
{
var queryString = new KeyValuePair<string, SugarParameter[]>(sql, pars);
//ToSqlExplain 在标题6中有完整代码
Console.WriteLine(ToSqlExplain.GetSql(queryString));//输出sql
};
ToSqlExplain.GetSql类中的方法(拼接出完整的Sql,方便查看)
public class ToSqlExplain { public static string GetSql(KeyValuePair<string, SugarParameter[]> queryString) { var sql = queryString.Key;//sql语句 var par = queryString.Value;//参数 //字符串替换MethodConst1x会替换掉MethodConst1所有要从后往前替换,不能用foreach,后续可以优化 for (int i = par.Length - 1; i >= 0; i--) { if (par[i].ParameterName.StartsWith("@") && par[i].ParameterName.Contains("UnionAll")) { sql = sql.Replace(par[i].ParameterName, par[i].Value.ToString()); } } for (int i = par.Length - 1; i >= 0; i--) { if (par[i].ParameterName.StartsWith("@Method")) { sql = sql.Replace(par[i].ParameterName, "'" + par[i].Value.ToString() + "'"); } } for (int i = par.Length - 1; i >= 0; i--) { if (par[i].ParameterName.StartsWith("@Const")) { sql = sql.Replace(par[i].ParameterName, par[i].Value.ToString()); } } for (int i = par.Length - 1; i >= 0; i--) { if (par[i].ParameterName.StartsWith("@")) { //值拼接单引号 拿出来的sql不会报错 sql = sql.Replace(par[i].ParameterName, "'" + Convert.ToString(par[i].Value) + "'"); } } return sql; } }
创建对象的时候指定语言
public enum LanguageType
{
Default=0, //中&英
Chinese=1, //处理过的异常尽量中文,未处理的还是英文
English=2 //全部英文
}
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
LanguageType=LanguageType.English,//只显示英文
IsAutoCloseConnection = true
});
IsAutoCloseConnection = true//自动释放
//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
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。