using cd.dapper.extension;
using Dapper;
using learun.util;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Threading.Tasks;
namespace learun.database.mysql
{
///
/// 版 本 EasyCode EC管理后台
/// Copyright (c) 2019-present EC管理有限公司
/// 创建人:tobin
/// 日 期:2019.09.09
/// 描 述:数据库操作方法实现
///
public class MySqlDataBase : IDataBase
{
private static ISqlAdapter sqlAdapter;
///
/// 当前使用的数据库链接对象
///
private DbConnection dbConnection { get; set; }
///
/// 事务对象
///
private DbTransaction dbTransaction { get; set; }
///
/// 构造函数
///
/// 数据库连接地址
public MySqlDataBase(string connString)
{
sqlAdapter = new MySqlAdapter();
dbConnection = new MySqlConnection(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> 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
{
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)
{
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 t1.*,
(select COLUMN_NAME from information_schema.`COLUMNS` where TABLE_SCHEMA=database() and TABLE_NAME =t1.name and COLUMN_KEY='PRI') pk
from (
SELECT TABLE_NAME name,0 reserved,0 data,0 index_size,TABLE_ROWS sumrows,0 unused, (select IF(LENGTH(TRIM(TABLE_COMMENT))<1,TABLE_NAME,TABLE_COMMENT)) tdescription
from information_schema.`TABLES` where TABLE_SCHEMA =database()
) t1 ORDER BY t1.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 ORDINAL_POSITION f_number, COLUMN_NAME f_column, DATA_TYPE f_datatype, if(CHARACTER_MAXIMUM_LENGTH is null,if(LOCATE('int',column_type)>0,REPLACE(REPLACE(column_type,'int(',''),')',''),0),CHARACTER_MAXIMUM_LENGTH) f_length, '' f_identity, IF(COLUMN_KEY='PRI','1','') f_key,
IF(IS_NULLABLE='YES','1','') f_isnullable,COLUMN_DEFAULT f_default,case when COLUMN_COMMENT='' then COLUMN_NAME else COLUMN_COMMENT END f_remark from (
select *
from information_schema.`COLUMNS` t1 where TABLE_SCHEMA=database() and TABLE_NAME = ?tableName
) t2 order by f_number ");
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 limit 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;
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(strSql + OrderBy);
sb.Append(" limit " + num + "," + pageSize + "");
return sb.ToString();
}
///
/// 格式化sql语句
///
/// sql语句
/// sql语句
private string SqlFormat(string strSql)
{
return strSql.Replace("@", "?");
}
#endregion 私有方法
}
}