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

https://www.donet5.com

6、在sqlSugar的帮助类中尽量避免  单例 SqlSugarClient ,也就是上述代码中的 红色部分,官方是不建议使用单例对象的,具体原因是:

偶发性错误 - SqlSugar 5x - .NET果糖网 (donet5.com)

在多线程下,可能会引发异常。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM