using cd.dapper.extension; using Dapper; using learun.util; using Oracle.ManagedDataAccess.Client; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Text; using System.Threading.Tasks; namespace learun.database.oracle { /// /// 版 本 EasyCode EC管理后台 /// Copyright (c) 2019-present EC管理有限公司 /// 创建人:tobin /// 日 期:2019.09.09 /// 描 述:数据库操作方法实现 /// public class OracleDataBase : IDataBase { private ISqlAdapter sqlAdapter; /// /// 当前使用的数据库链接对象 /// private DbConnection dbConnection { get; set; } /// /// 事务对象 /// private DbTransaction dbTransaction { get; set; } /// /// 构造函数 /// /// 数据库连接地址 public OracleDataBase(string connString) { sqlAdapter = new OracleAdapter(); dbConnection = new OracleConnection(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 { strSql = SqlFormat(strSql); 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); sql = SqlFormat(sql); 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 { sql = SqlFormat(sql); 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; } } sql = SqlFormat(sql); 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 { sql = SqlFormat(sql); 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 { sql = SqlFormat(sql); 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; } } sql = SqlFormat(sql); 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 { sql = SqlFormat(sql); 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 { sql = SqlFormat(sql); 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<(IEnumerable list, int total)> FindList(string sql, object param, string orderField, bool isAsc, int pageSize, int pageIndex) { try { sql = SqlFormat(sql); 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> 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 { sql = SqlFormat(sql); 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 { sql = SqlFormat(sql); 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(@" select distinct col.table_name name, 0 reserved, 0 fdata, 0 index_size, nvl(t.num_rows, 0) sumrows, 0 funused, tab.comments tdescription, column_name pk from user_cons_columns col inner join user_constraints con on con.constraint_name = col.constraint_name inner join user_tab_comments tab on tab.table_name = col.table_name inner join user_tables t on t.TABLE_NAME = col.table_name where con.constraint_type not in ('C', 'R') ORDER BY col.table_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 col.column_id f_number, col.column_name f_column, col.data_type f_datatype, col.data_length f_length, NULL f_identity, CASE uc.constraint_type WHEN 'P' THEN 1 ELSE NULL END f_key, CASE col.nullable WHEN 'N' THEN 0 ELSE 1 END f_isnullable, col.data_default f_defaults, NVL(comm.comments, col.column_name) AS f_remark FROM user_tab_columns col INNER JOIN user_col_comments comm ON comm.TABLE_NAME = col.TABLE_NAME AND comm.COLUMN_NAME = col.COLUMN_NAME LEFT JOIN user_cons_columns ucc ON ucc.table_name = col.table_name AND ucc.column_name = col.column_name AND ucc.position = 1 LEFT JOIN user_constraints uc ON uc.constraint_name = ucc.constraint_name AND uc.constraint_type = 'P' WHERE col.table_name = :tableName ORDER BY col.column_id"); 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 * from(" + strSql + ")t where rownum=1"; 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"); } } sb.Append("Select * From (Select ROWNUM lrrn,"); sb.Append(" T.* From (" + strSql + OrderBy + ") T ) N Where lrrn > " + num + " And lrrn <= " + num1 + ""); return sb.ToString(); } /// /// 格式化sql语句 /// /// sql语句 /// sql语句 private string SqlFormat(string strSql) { return strSql.Replace("@", ":"); } #endregion 私有方法 } }