using cd.dapper.extension; using Dapper; using learun.util; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace learun.database.sqlserver { /// /// 版 本 EasyCode EC管理后台 /// Copyright (c) 2019-present EC管理有限公司 /// 创建人:tobin /// 日 期:2019.09.09 /// 描 述:数据库操作方法实现 /// public class SqlserverDataBase : IDataBase { private ISqlAdapter sqlAdapter; /// /// 当前使用的数据库链接对象 /// private DbConnection dbConnection { get; set; } /// /// 事务对象 /// private DbTransaction dbTransaction { get; set; } /// /// 构造函数 /// /// 数据库连接地址 public SqlserverDataBase(string connString) { sqlAdapter = new SqlserverAdapter(); dbConnection = new SqlConnection(connString); } #region 事务 /// /// 开启事务 /// /// The trans. public IDataBase BeginTrans() { if (dbConnection.State == ConnectionState.Closed) { dbConnection.Open(); } dbTransaction = dbConnection.BeginTransaction(); return this; } /// /// 提交 /// public void Commit() { try { dbTransaction.Commit(); } catch { throw; } finally { this.Close(); } } /// /// 把当前操作回滚成未提交状态 /// public void Rollback() { try { dbTransaction.Rollback(); } catch { throw; } finally { this.Close(); } } /// /// 关闭连接 内存回收 /// public void Close() { if (dbTransaction != null) { dbTransaction.Dispose(); dbTransaction = null; } if (dbConnection != null) { dbConnection.Close(); dbConnection.Dispose(); dbConnection = null; } } #endregion 事务 #region 执行sql语句 /// /// 执行sql语句(带参数) /// /// sql语句 /// 参数 /// public async Task ExecuteSql(string strSql, object param = null) { try { var res = await dbConnection.ExecuteAsync(strSql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } #endregion 执行sql语句 #region 执行存储过程 /// /// 执行存储过程 /// /// 存储过程名称 /// 参数 /// public async Task ExecuteProc(string procName, object param = null) { try { var res = await dbConnection.ExecuteAsync(procName, param, dbTransaction, null, CommandType.StoredProcedure); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 执行存储过程(查询实体数据) /// /// 存储过程名称 /// 参数 /// public async Task ExecuteProc(string procName, object param = null) where T : class { try { var res = await dbConnection.QueryFirstAsync(procName, param, dbTransaction, null, CommandType.StoredProcedure); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 执行存储过程(查询实体数据) /// /// /// 存储过程名称. /// 参数 public async Task QueryFirstProc(string procName, object param = null) { try { var res = await dbConnection.QueryFirstAsync(procName, param, dbTransaction, null, CommandType.StoredProcedure); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 执行存储过程(获取列表数据) /// /// 存储过程名称 /// 参数 /// public async Task> QueryProc(string procName, object param = null) where T : class { try { var res = await dbConnection.QueryAsync(procName, param, dbTransaction, null, CommandType.StoredProcedure); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 执行存储过程(获取列表数据) /// /// 存储过程名称 /// 参数 /// public async Task> QueryProc(string procName, object param = null) { try { var res = await dbConnection.QueryAsync(procName, param, dbTransaction, null, CommandType.StoredProcedure); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } #endregion 执行存储过程 #region 对像实体 新增/修改/删除 /// /// 插入实体数据 /// /// 类型 /// 实体数据 /// public async Task Insert(T entity) where T : class { try { string sql = SqlHelper.Insert(sqlAdapter); var res = await dbConnection.ExecuteAsync(sql, entity, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 更新实体数据 /// /// /// 实体数据 /// 是否只更新有值的字段 /// 类型 public async Task Update(T entity, bool isOnlyHasValue = true) where T : class { try { string sql = ""; if (isOnlyHasValue) { var args = entity.ToJson().ToJObject(); List hasNoValueList = new List(); List nullValueList = new List(); foreach (var item in args.Properties()) { if (item.Value.Type == Newtonsoft.Json.Linq.JTokenType.Null) { hasNoValueList.Add(item.Name); } else if (item.Value.ToString() == "" || item.Value.ToString() == "1000-01-01 00:00:00") { nullValueList.Add(item.Name); } } sql = SqlHelper.Update(sqlAdapter, hasNoValueList); foreach (var item in nullValueList) { sql = sql.Replace("?" + item, "null"); } } else { sql = SqlHelper.Update(sqlAdapter); } var res = await dbConnection.ExecuteAsync(sql, entity, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 删除实体数据 /// /// /// 实体数据 /// 类型 public async Task Delete(T entity) where T : class { try { string sql = SqlHelper.Delete(sqlAdapter); var res = await dbConnection.ExecuteAsync(sql, entity, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 删除数据根据给定的字段值 /// /// /// 参数 /// 类型 public async Task DeleteAny(object param) where T : class { try { if (param == null) { param = new { }; } var jparam = param.ToJson().ToJObject(); List fields = new List(); foreach (var item in jparam.Properties()) { if (!string.IsNullOrEmpty(item.Value.ToString())) { fields.Add(item.Name); } } string sql = SqlHelper.Delete(sqlAdapter, fields); var res = await dbConnection.ExecuteAsync(sql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } #endregion 对像实体 新增/修改/删除 #region 对象实体查询 /// /// 获取单个实体数据 /// /// 单个实体数据 /// 主键 /// public async Task FindEntityByKey(object keyValue) where T : class { try { string sql = SqlHelper.Select(sqlAdapter); var res = await dbConnection.QueryFirstOrDefaultAsync(sql, new { id = keyValue }, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取单个实体数据 /// /// 单个实体数据 /// sql语句 /// 参数 /// public async Task FindEntity(string sql, object param = null) where T : class { try { var res = await dbConnection.QueryFirstOrDefaultAsync(sql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取单个实体数据 /// /// 单个实体数据 /// 参数 /// public async Task FindEntity(object param) where T : class { try { if (param == null) { param = new { }; } string sql = SqlHelper.SelectAll(sqlAdapter) + " where 1=1 "; var jparam = param.ToJson().ToJObject(); foreach (var item in jparam.Properties()) { if (!string.IsNullOrEmpty(item.Value.ToString())) { sql += " AND " + item.Name + "=@" + item.Name; } } var res = await dbConnection.QueryFirstOrDefaultAsync(sql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取单个实体数据 /// /// 单个实体数据 /// sql语句. /// 参数. public async Task FindEntity(string sql, object param = null) { try { var res = await dbConnection.QueryFirstOrDefaultAsync(sql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取数据列表 /// /// 列表数据 /// sql语句. /// 参数. /// 类型. public async Task> FindList(string sql, object param = null) where T : class { try { var res = await dbConnection.QueryAsync(sql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取数据列表 /// /// 列表数据 /// 参数. /// 类型. public async Task> FindList(object param) where T : class { try { if (param == null) { param = new { }; } string sql = SqlHelper.SelectAll(sqlAdapter) + " where 1=1 "; var jparam = param.ToJson().ToJObject(); foreach (var item in jparam.Properties()) { if (!string.IsNullOrEmpty(item.Value.ToString())) { sql += " AND " + item.Name + "=@" + item.Name; } } var res = await dbConnection.QueryAsync(sql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取数据列表 /// /// 列表数据 /// sql语句. /// 参数. public async Task> FindList(string sql, object param = null) { try { var res = await dbConnection.QueryAsync(sql, param, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取数据列表(分页) /// /// 列表数据 /// sql语句 /// 参数 /// 排序字段 /// 排序类型 /// 每页数据条数 /// 页码 /// public async Task<(IEnumerable list, int total)> FindList(string sql, object param, string orderField, bool isAsc, int pageSize, int pageIndex) where T : class { try { StringBuilder sb = new StringBuilder(); sb.Append(GetPageSql(sql, orderField, isAsc, pageSize, pageIndex)); var resTotal = await dbConnection.ExecuteScalarAsync("Select Count(1) From (" + sql + ") As t", param, dbTransaction); int total = Convert.ToInt32(resTotal); var list = await dbConnection.QueryAsync(sb.ToString(), param, dbTransaction); return (list, total); } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取数据列表(分页) /// /// /// sql语句 /// 参数 /// 分页参数 /// public async Task> FindList(string sql, object param, Pagination pagination) where T : class { bool isAsc = true && (string.IsNullOrEmpty(pagination.sord) || pagination.sord.ToUpper() == "ASC"); var (list, total) = await FindList(sql, param, pagination.sidx, isAsc, pagination.rows, pagination.page); pagination.records = total; return list; } /// /// 获取数据列表(分页) /// /// 列表数据 /// sql语句 /// 参数 /// 排序字段 /// 排序类型 /// 每页数据条数 /// 页码 public async Task<(IEnumerable list, int total)> FindList(string sql, object param, string orderField, bool isAsc, int pageSize, int pageIndex) { try { StringBuilder sb = new StringBuilder(); sb.Append(GetPageSql(sql, orderField, isAsc, pageSize, pageIndex)); var resTotal = await dbConnection.ExecuteScalarAsync("Select Count(1) From (" + sql + ") As t", param, dbTransaction); int total = Convert.ToInt32(resTotal); var list = await dbConnection.QueryAsync(sb.ToString(), param, dbTransaction); return (list, total); } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取数据列表(分页) /// /// sql语句 /// 参数 /// 分页参数 /// public async Task> FindList(string sql, object param, Pagination pagination) { bool isAsc = true && (string.IsNullOrEmpty(pagination.sord) || pagination.sord.ToUpper() == "ASC"); var (list, total) = await FindList(sql, param, pagination.sidx, isAsc, pagination.rows, pagination.page); pagination.records = total; return list; } /// /// 获取表的所有数据 /// /// 列表数据 /// public async Task> FindAll() where T : class { try { string sql = SqlHelper.SelectAll(sqlAdapter); var res = await dbConnection.QueryAsync(sql, null, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } #endregion 对象实体查询 #region 数据源查询 /// /// 查询方法,返回datatable /// /// datatable数据 /// sql语句 /// 参数 public async Task FindTable(string sql, object param = null) { try { var IDataReader = await dbConnection.ExecuteReaderAsync(sql, param, dbTransaction); var dt = DBCommonHelper.IDataReaderToDataTable(IDataReader); IDataReader.Dispose(); return dt; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 分页查询方法,返回datatable /// /// datatable数据 /// sql语句 /// 参数 /// 排序字段 /// 排序类型 /// 每页数据条数 /// 页码 public async Task<(DataTable list, int total)> FindTable(string sql, object param, string orderField, bool isAsc, int pageSize, int pageIndex) { try { StringBuilder sb = new StringBuilder(); sb.Append(GetPageSql(sql, orderField, isAsc, pageSize, pageIndex)); int total = Convert.ToInt32(await dbConnection.ExecuteScalarAsync("Select Count(1) From (" + sql + ") As t", param, dbTransaction)); var IDataReader = await dbConnection.ExecuteReaderAsync(sb.ToString(), param, dbTransaction); var dt = DBCommonHelper.IDataReaderToDataTable(IDataReader); IDataReader.Dispose(); return (dt, total); } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 分页查询方法,返回datatable /// /// sql语句 /// 参数 /// 分页参数 /// public async Task FindTable(string sql, object param, Pagination pagination) { bool isAsc = true && (string.IsNullOrEmpty(pagination.sord) || pagination.sord.ToUpper() == "ASC"); var (list, total) = await FindTable(sql, param, pagination.sidx, isAsc, pagination.rows, pagination.page); pagination.records = total; return list; } #endregion 数据源查询 #region 获取数据库表信息 /// /// 获取数据库表信息 /// /// 数据库表信息 public async Task> GetDataBaseTable() { try { StringBuilder strSql = new StringBuilder(); strSql.Append(@"DECLARE @TableInfo TABLE ( name VARCHAR(50) , sumrows VARCHAR(11) , reserved VARCHAR(50) , data VARCHAR(50) , index_size VARCHAR(50) , unused VARCHAR(50) , pk VARCHAR(50) ) DECLARE @TableName TABLE ( name VARCHAR(50) ) DECLARE @name VARCHAR(50) DECLARE @pk VARCHAR(50) INSERT INTO @TableName ( name ) SELECT o.name FROM sysobjects o , sysindexes i WHERE o.id = i.id AND o.Xtype = 'U' AND i.indid < 2 ORDER BY i.rows DESC , o.name WHILE EXISTS ( SELECT 1 FROM @TableName ) BEGIN SELECT TOP 1 @name = name FROM @TableName DELETE @TableName WHERE name = @name DECLARE @objectid INT SET @objectid = OBJECT_ID(@name) SELECT @pk = COL_NAME(@objectid, colid) FROM sysobjects AS o INNER JOIN sysindexes AS i ON i.name = o.name INNER JOIN sysindexkeys AS k ON k.indid = i.indid WHERE o.xtype = 'PK' AND parent_obj = @objectid AND k.id = @objectid INSERT INTO @TableInfo ( name , sumrows , reserved , data , index_size , unused ) EXEC sys.sp_spaceused @name UPDATE @TableInfo SET pk = @pk WHERE name = @name END SELECT F.name as name, F.reserved as reserved, F.data as data, F.index_size as index_size, RTRIM(F.sumrows) AS sumrows , F.unused as unused, ISNULL(p.tdescription, f.name) AS tdescription , F.pk as pk FROM @TableInfo F LEFT JOIN ( SELECT name = CASE WHEN A.COLORDER = 1 THEN D.NAME ELSE '' END , tdescription = CASE WHEN A.COLORDER = 1 THEN ISNULL(F.VALUE, '') ELSE '' END FROM SYSCOLUMNS A LEFT JOIN SYSTYPES B ON A.XUSERTYPE = B.XUSERTYPE INNER JOIN SYSOBJECTS D ON A.ID = D.ID AND D.XTYPE = 'U' AND D.NAME <> 'DTPROPERTIES' LEFT JOIN sys.extended_properties F ON D.ID = F.major_id WHERE a.COLORDER = 1 AND F.minor_id = 0 ) P ON F.name = p.name ORDER BY f.name "); var res = await dbConnection.QueryAsync(strSql.ToString(), null, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取表的字段信息 /// /// 表的字段信息 /// 表名 public async Task> GetDataBaseTableFields(string tableName) { try { StringBuilder strSql = new StringBuilder(); strSql.Append(@"SELECT [f_number] = a.colorder , [f_column] = a.name , [f_datatype] = b.name , [f_length] = COLUMNPROPERTY(a.id, a.name, 'PRECISION') , [f_identity] = CASE WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1 THEN '1' ELSE '' END , [f_key] = CASE WHEN EXISTS ( SELECT 1 FROM sysobjects WHERE xtype = 'PK' AND parent_obj = a.id AND name IN ( SELECT name FROM sysindexes WHERE indid IN ( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid = a.colid ) ) ) THEN '1' ELSE '' END , [f_isnullable] = CASE WHEN a.isnullable = 1 THEN '1' ELSE '' END , [f_defaults] = ISNULL(e.text, '') , [f_remark] = ISNULL(g.[value], a.name) FROM syscolumns a LEFT JOIN systypes b ON a.xusertype = b.xusertype INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault = e.id LEFT JOIN sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id LEFT JOIN sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 WHERE d.name = @tableName ORDER BY a.id , a.colorder"); var res = await dbConnection.QueryAsync(strSql.ToString(), new { tableName }, dbTransaction); return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取数据库地址信息 /// /// 数据库地址信息 public string GetDataSource() { try { return dbConnection.DataSource; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 测试数据库是否能链接成功 /// /// The connection. public string TestConnection() { try { BeginTrans(); Commit(); return "success"; } catch (Exception ex) { return ex.Message; } finally { if (dbTransaction == null) { this.Close(); } } } /// /// 获取sql语句的字段 /// /// sql语句 /// public async Task> GetSqlColName(string strSql) { try { DataTable dt = null; strSql = "select TOP 1 * from(" + strSql + ")t"; var IDataReader = await dbConnection.ExecuteReaderAsync(strSql, null, dbTransaction); dt = DBCommonHelper.IDataReaderToDataTable(IDataReader); List res = new List(); foreach (DataColumn item in dt.Columns) { res.Add(item.ColumnName); } return res; } catch (Exception ex) { throw ex; } finally { if (dbTransaction == null) { this.Close(); } } } #endregion 获取数据库表信息 #region 私有方法 /// /// 获取分页语句 /// /// /// sql语句 /// 排序字段 /// 是否是升序 /// 每一页大小 /// 页码 private string GetPageSql(string strSql, string orderField, bool isAsc, int pageSize, int pageIndex) { StringBuilder sb = new StringBuilder(); if (pageIndex == 0) { pageIndex = 1; } int num = (pageIndex - 1) * pageSize; int num1 = (pageIndex) * pageSize; string OrderBy = ""; if (!string.IsNullOrEmpty(orderField)) { if (orderField.ToUpper().IndexOf("ASC", StringComparison.Ordinal) + orderField.ToUpper().IndexOf("DESC", StringComparison.Ordinal) > 0) { OrderBy = " Order By " + orderField; } else { OrderBy = " Order By " + orderField + " " + (isAsc ? "ASC" : "DESC"); } } else { OrderBy = "order by (select 0)"; } sb.Append("Select * From (Select ROW_NUMBER() Over (" + OrderBy + ")"); sb.Append(" As rowNum, * From (" + strSql + ") T ) As N Where rowNum > " + num + " And rowNum <= " + num1 + ""); return sb.ToString(); } #endregion 私有方法 } }