(精华)2020年6月27日 C#类库 DbHelper(Ado.net数据库封装)

using EFCore.Sharding;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;

namespace Core.Util
{
    /// 
    /// 描述:数据库操作抽象帮助类
    /// 
    public abstract class DbHelper
    {
        #region 构造函数

        /// 
        /// 构造函数
        /// 
        /// 数据库类型
        /// 完整连接字符串
        public DbHelper(DatabaseType dbType, string conString)
        {
            _dbType = dbType;
            _conString = conString;
        }

        #endregion

        #region 私有成员

        /// 
        /// 数据库类型
        /// 
        protected DatabaseType _dbType;

        /// 
        /// 连接字符串
        /// 
        protected string _conString;

        /// 
        /// 实体需要引用的额外命名空间
        /// 
        protected string _extraUsingNamespace { get; set; } = string.Empty;

        /// 
        /// 类型映射字典
        /// 
        protected abstract Dictionary<string, Type> DbTypeDic { get; }

        #endregion

        #region 外部接口

        /// 
        /// 通过数据库连接字符串和Sql语句查询返回DataTable
        /// 
        /// Sql语句
        /// 
        public DataTable GetDataTableWithSql(string sql)
        {
            DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType);
            using (DbConnection conn = dbProviderFactory.CreateConnection())
            {
                conn.ConnectionString = _conString;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                using (DbCommand cmd = conn.CreateCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sql;

                    DbDataAdapter adapter = dbProviderFactory.CreateDataAdapter();
                    adapter.SelectCommand = cmd;
                    DataSet table = new DataSet();
                    adapter.Fill(table);

                    return table.Tables[0];
                }
            }
        }

        /// 
        /// 通过数据库连接字符串和Sql语句查询返回DataTable,参数化查询
        /// 
        /// Sql语句
        /// 参数
        /// 
        public DataTable GetDataTableWithSql(string sql, List<DbParameter> parameters)
        {
            DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType);
            using (DbConnection conn = dbProviderFactory.CreateConnection())
            {
                conn.ConnectionString = _conString;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                using (DbCommand cmd = conn.CreateCommand())
                {

                    cmd.Connection = conn;
                    cmd.CommandText = sql;
                    if (parameters != null && parameters.Count > 0)
                    {
                        foreach (var item in parameters)
                        {
                            cmd.Parameters.Add(item);
                        }
                    }

                    DbDataAdapter adapter = dbProviderFactory.CreateDataAdapter();
                    adapter.SelectCommand = cmd;
                    DataSet table = new DataSet();
                    adapter.Fill(table);
                    cmd.Parameters.Clear();

                    return table.Tables[0];
                }
            }
        }

        /// 
        /// 通过数据库连接字符串和Sql语句查询返回List
        /// 
        /// 实体类
        /// Sql语句
        /// 
        public List<T> GetListBySql<T>(string sqlStr)
        {
            return GetDataTableWithSql(sqlStr).ToList<T>();
        }

        /// 
        /// 通过数据库连接字符串和Sql语句查询返回List,参数化查询
        /// 
        /// 实体类
        /// Sql语句
        /// 查询参数
        /// 
        public List<T> GetListBySql<T>(string sqlStr, List<DbParameter> param)
        {
            return GetDataTableWithSql(sqlStr, param).ToList<T>();
        }

        /// 
        /// 执行无返回值的Sql语句
        /// 
        /// Sql语句
        public int ExecuteSql(string sql)
        {
            int count = 0;
            DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType);
            using (DbConnection conn = dbProviderFactory.CreateConnection())
            {
                conn.ConnectionString = _conString;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                using (DbCommand cmd = dbProviderFactory.CreateCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sql;
                    count = cmd.ExecuteNonQuery();

                    return count;
                }
            }
        }

        /// 
        /// 执行无返回值的Sql语句
        /// 
        /// Sql语句
        /// 
        public int ExecuteSql(string sql, List<DbParameter> paramters)
        {
            int count = 0;
            DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType);
            using (DbConnection conn = dbProviderFactory.CreateConnection())
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                using (DbCommand cmd = dbProviderFactory.CreateCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sql;

                    if (paramters != null && paramters.Count > 0)
                    {
                        foreach (var item in paramters)
                        {
                            cmd.Parameters.Add(item);
                        }
                    }
                    count = cmd.ExecuteNonQuery();

                    return count;
                }
            }
        }

        /// 
        /// 获取数据库中的所有表
        /// 
        /// 模式(架构)
        /// 
        public abstract List<DbTableInfo> GetDbAllTables(string schemaName = null);

        /// 
        /// 通过连接字符串和表名获取数据库表的信息
        /// 
        /// 表名
        /// 
        public abstract List<TableInfo> GetDbTableInfo(string tableName);

        /// 
        /// 将数据库类型转为对应C#数据类型
        /// 
        /// 数据类型
        /// 
        public virtual Type DbTypeStr_To_CsharpType(string dbTypeStr)
        {
            string _dbTypeStr = dbTypeStr.ToLower();
            Type type = null;
            if (DbTypeDic.ContainsKey(_dbTypeStr))
                type = DbTypeDic[_dbTypeStr];
            else
                type = typeof(string);

            return type;
        }

        /// 
        /// 生成实体文件
        /// 
        /// 表字段信息
        /// 表名
        /// 表描述信息
        /// 文件路径(包含文件名)
        /// 实体命名空间
        /// 架构(模式)名
        public virtual void SaveEntityToFile(List<TableInfo> infos, string tableName, string tableDescription, string filePath, string nameSpace, string schemaName = null)
        {
            string properties = "";
            string schema = "";
            if (!schemaName.IsNullOrEmpty())
                schema = $@", Schema = ""{schemaName}""";
            infos.ForEach((item, index) =>
            {
                string isKey = item.IsKey ? $@"
        [Key, Column(Order = {index + 1})]" : "";
                Type type = DbTypeStr_To_CsharpType(item.Type);
                string isNullable = item.IsNullable && type.IsValueType ? "?" : "";
                string description = item.Description.IsNullOrEmpty() ? item.Name : item.Description;
                string newPropertyStr =
$@"
        /// 
        /// {description}
        /// {isKey}
        public {type.Name}{isNullable} {item.Name} {{ get; set; }}
";
                properties += newPropertyStr;
            });
            string fileStr =
$@"using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
{_extraUsingNamespace}
namespace {nameSpace}
{{
    /// 
    /// {tableDescription}
    /// 
    [Table(""{tableName}""{schema})]
    public class {tableName}
    {{
{properties}
    }}
}}";
            FileHelper.WriteTxt(fileStr, filePath, FileMode.Create);
        }

        #endregion
    }
}

你可能感兴趣的:(#,C#类库/数据库)