
2.编写helper类
using SqlSugar;
namespace xxx.Helper.DB
{
public static class SqlSugarHelper
{
private static SqlSugarScope _db;
static SqlSugarHelper()
{
string mysqlConnectionStr = AppSettingsHelper.Configuration["DB:MySQLConnStr"] ?? "";
// 初始化数据库连接
_db = new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = mysqlConnectionStr,// "server=localhost;port=3306;database=testdb;user=root;password=123456;",
DbType = SqlSugar.DbType.MySql,
IsAutoCloseConnection = true, // 自动关闭连接
InitKeyType = InitKeyType.Attribute, // 从特性读取主键和自增列信息
//ConfigureExternalServices = new ConfigureExternalServices()
//{
// EntityService = (c, p) =>
// {
// // 设置列的默认值
// if (p.IsPrimarykey == false && p.PropertyName == "Id")
// {
// p.IsIgnore = true; // 忽略非主键的Id列
// }
// }
//}
});
//// 设置AOP事件
//_db.Aop.OnLogExecuting = (sql, pars) =>
//{
// Console.WriteLine($"SQL: {sql}");
// Console.WriteLine($"Parameters: {string.Join(", ", pars.Select(p => $"{p.ParameterName}:{p.Value}"))}");
//};
_db.Aop.OnError = (exp) =>
{
Console.WriteLine($"SQL Error: {exp.Sql}");
Console.WriteLine($"Error Message: {exp.Message}");
};
}
// 获取数据库实例
public static SqlSugarScope Db => _db;
// 查询多个对象(使用 SQL)
public static List<T> GetList<T>(string sql, object parameters = null) where T : class, new()
{
return _db.Ado.SqlQuery<T>(sql, parameters);
}
public static void ExcuteSqlString(string sql, object parameters = null)
{
_db.Ado.ExecuteCommand(sql, parameters);
}
}
}