NuGet安装: SqlSugarCore
cpp
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Namespace
{
public class SqlSugarHelper
{
public string _connectionString = CustomConfigManager.GetConfig("MySql");//MySql连接字符串
public SqlSugarClient _db = null;
/// <summary>
/// 构造函数(初始化)
/// 调用方法:
/// SqlSugarHelper sugar = new SqlSugarHelper();
/// var db = sugar.SqlClient();
/// var user = db.Queryable<Userinfo>().Where(a => a.Name.Equals(uid) && a.PWD.Equals(pwd)).ToList().FirstOrDefault();
/// </summary>
public SqlSugarClient SqlClient()
{
if (string.IsNullOrEmpty(_connectionString))
throw new ArgumentNullException("数据库连接字符串为空");
_db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = _connectionString,//数据库连接字符串,见UI的appsettings.json内配置
DbType = DbType.MySql,//数据库类型
IsAutoCloseConnection = true,//自动断开连接
MoreSettings = new ConnMoreSettings()
{
IsWithNoLockQuery = true,//为true表式查询的时候默认会加上.With(SqlWith.NoLock),
IsAutoRemoveDataCache = true//为true自动清除缓存
}
});
//输入最终SQL语句...
_db.Aop.OnLogExecuting = (sql, pars) =>
{
var s1 = sql;//断点打在这里看内部生成的sql语句...
};
return _db;
}
}
}
config文件:
cs
{
//MySql连接字符串
"MySql": "Server=127.0.0.1;Database=db_test;User ID=root;Password=123456;SslMode=None;allowPublicKeyRetrieval=true;"//开发环境
}
调用举例:
cs
//查询
public static List<tb_equip> Get_EquipList()
{
SqlSugarHelper sugar = new SqlSugarHelper();
var db = sugar.SqlClient();
try
{
var gsList = db.Queryable<tb_equip>()
.Where(a => a.IsUsing == true)//使用中
.WhereIF(!string.IsNullOrWhiteSpace(PowerStation), a => a.PowerStation.Equals(PowerStation))//可选条件
.ToList();
return gsList;
}
catch (Exception ex)
{
Console.WriteLine("Get_TH70M_EquipList() " + ex.Message);//打印结果
return null;
}
}
//添加
public static bool tb_tcp_log_add(Socket send, decimal wd_dec, decimal sd_dec, tb_equip equip, string packet, TcpType tcpType)
{
SqlSugarHelper sugar = new SqlSugarHelper();
var db = sugar.SqlClient();
tb_tcp_log log = new tb_tcp_log();
log.TCP_IP_STR = send.RemoteEndPoint.ToString();//IP原文
log.TCP_IP = Tools.SocketFormat(send.RemoteEndPoint.ToString());//IP格式化
log.UUID = Guid.NewGuid().ToString();//主键(必须)
log.Type = tcpType.ToString(); //类型
int cc = db.Insertable(log).ExecuteCommand();//添加到数据库
Console.WriteLine($"添加到数据库,成功添加{cc}条...");//打印结果
if (cc > 0)
{
WriteLineAndLog("已添加");
}
return cc > 0;
}