|
|
|
|
using MaterialTraceability.Common;
|
|
|
|
|
using SqlSugar;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace MaterialTraceability.SqlSugar
|
|
|
|
|
{
|
|
|
|
|
public class SqlGenerator
|
|
|
|
|
{
|
|
|
|
|
public static string ConnectionString = "Data Source=172.21.29.56;Port=6066;Initial Catalog=ry;uid=root; pwd=root";
|
|
|
|
|
private static SqlSugarClient sqlSugarClient = null;
|
|
|
|
|
|
|
|
|
|
private static readonly object lockHelper = new object();
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 连接服务器数据库
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public static SqlSugarClient GetMySqlInstance()
|
|
|
|
|
{
|
|
|
|
|
if (sqlSugarClient == null)
|
|
|
|
|
{
|
|
|
|
|
lock (lockHelper)
|
|
|
|
|
{
|
|
|
|
|
//单例模式,避免多次实例化
|
|
|
|
|
if (sqlSugarClient == null)
|
|
|
|
|
{
|
|
|
|
|
sqlSugarClient = new SqlSugarClient(new ConnectionConfig()
|
|
|
|
|
{
|
|
|
|
|
//数据库类型
|
|
|
|
|
DbType = DbType.MySql,
|
|
|
|
|
//数据库连接字符串
|
|
|
|
|
ConnectionString = ConnectionString,
|
|
|
|
|
InitKeyType = InitKeyType.Attribute,
|
|
|
|
|
//是否自动关闭连接
|
|
|
|
|
IsAutoCloseConnection = true,
|
|
|
|
|
//AopEvents = new AopEvents
|
|
|
|
|
//{
|
|
|
|
|
// //记录执行SQL和参数
|
|
|
|
|
// OnLogExecuting = (sql, p) =>
|
|
|
|
|
// {
|
|
|
|
|
// LogHelper.SqlLog(sql);
|
|
|
|
|
// }
|
|
|
|
|
//}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
//可注释
|
|
|
|
|
sqlSugarClient.Aop.OnLogExecuting = (sql, pars) => //SQL执行中事件
|
|
|
|
|
{
|
|
|
|
|
Parallel.For(0, 1, e =>
|
|
|
|
|
{
|
|
|
|
|
string SqlLog = "";
|
|
|
|
|
foreach (string item in new string[] { GetParas(pars), "【SQL语句】:" + sql })
|
|
|
|
|
{
|
|
|
|
|
SqlLog = SqlLog + item;
|
|
|
|
|
}
|
|
|
|
|
LogHelper.SqlLog(SqlLog);
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
return sqlSugarClient;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static string GetParas(SugarParameter[] pars)
|
|
|
|
|
{
|
|
|
|
|
string key = "【SQL参数】";
|
|
|
|
|
foreach (var param in pars)
|
|
|
|
|
{
|
|
|
|
|
key += $"{param.ParameterName}:{param.Value}\n";
|
|
|
|
|
}
|
|
|
|
|
LogHelper.SqlLog(key);
|
|
|
|
|
return key;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//官方建议 不单例 SqlSugarClient 对象 ,在多线程下,可能会引发异常。
|
|
|
|
|
public static SqlSugarClient GetSQLServerInstance()
|
|
|
|
|
{
|
|
|
|
|
return new SqlSugarClient(new ConnectionConfig()
|
|
|
|
|
{
|
|
|
|
|
DbType = DbType.MySql,
|
|
|
|
|
ConnectionString = ConnectionString,
|
|
|
|
|
InitKeyType = InitKeyType.Attribute,
|
|
|
|
|
IsAutoCloseConnection = true,
|
|
|
|
|
AopEvents = new AopEvents
|
|
|
|
|
{
|
|
|
|
|
OnLogExecuting = (sql, p) =>
|
|
|
|
|
{
|
|
|
|
|
//log.Debug(sql);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|