SqlSugar可同时连接多种类数据库的 daonet框架
1、官方中文文档
https://www.donet5.com/home/Doc
2、引入NuGet包
3、数据库访问类
using SqlSugar; using System.Configuration; using log4net; namespace Dao { public class SqlGenerator { private static readonly ILog log = LogManager.GetLogger(typeof(SqlGenerator)); public static string ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; private static SqlSugarClient sqlSugarClient = null; private static readonly object lockHelper = new object(); /// <summary> /// 连接Oracle数据库 /// </summary> /// <returns></returns> public static SqlSugarClient GetOracleInstance() { if (sqlSugarClient == null) { lock (lockHelper) {
//此写法,官方不推荐 //单例模式,避免多次实例化 if (sqlSugarClient == null) { sqlSugarClient = new SqlSugarClient(new ConnectionConfig() { //数据库类型 DbType = DbType.Oracle, //数据库连接字符串 ConnectionString = ConnectionString, InitKeyType = InitKeyType.Attribute, //是否自动关闭连接 IsAutoCloseConnection = true, AopEvents = new AopEvents { //记录执行SQL和参数 OnLogExecuting = (sql, p) => { log.Debug(sql); } } }); } } } return sqlSugarClient; }
//官方建议 不单例 SqlSugarClient 对象 public SqlSugarClient GetSQLServerInstance() { return new SqlSugarClient(new ConnectionConfig() { DbType = DbType.SqlServer, ConnectionString = ConnectionString, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true, AopEvents = new AopEvents { OnLogExecuting = (sql, p) => { log.Debug(sql); } } }); } } }
4、使用
//获取数据访问类对象 SqlSugarClient sqlServerDB = SqlGenerator.GetSQLServerInstance(); //调用查询方法 sqlServerDB.Ado.SqlQuery<CommonTable>(sql).ToList();
5、增、删、改 及查询更多更详细的方法,请参照官方帮助文档
https://www.donet5.com/home/Doc
6、在sqlSugar的帮助类中尽量避免 单例 SqlSugarClient ,也就是上述代码中的 红色部分,官方是不建议使用单例对象的,具体原因是:
偶发性错误 - SqlSugar 5x - .NET果糖网 (donet5.com)
在多线程下,可能会引发异常。
本文作者:Journey&Flower
本文链接:https://www.cnblogs.com/JourneyOfFlower/p/14981731.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步