using MySql.Data.MySqlClient; using MySqlX.XDevAPI.Common; using System; using System.Collections.Generic; using System.Data; using System.Text; using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace Opsoft.NetCore.O3App.Services.CommonFunction { public class MySqlUtils : IDisposable { #region 构造函数 public MySqlUtils() { } #endregion #region 连接字符串 private string _connectionString; public string ConnectionString { get { return _connectionString; } set { _connectionString = value; } } #endregion #region 数据库连接 /// /// 数据库连接 /// public MySqlConnection Connection { get; set; } #endregion #region 获取连接 /// /// /// /// public MySqlConnection GetConnection() { try { if (Connection == null) { Connection = new MySqlConnection(); Connection.ConnectionString = _connectionString; } if (Connection.State == ConnectionState.Broken) { Connection.Close(); } if (Connection.State == ConnectionState.Closed) { Connection.ConnectionString = _connectionString; Connection.Open(); } return Connection; } catch (Exception ex) { throw new Exception("获取连接失败.\r\n" + ex.Message); } } #endregion #region 销毁对象 /// /// /// public void Dispose() { if (Connection != null) { if (Connection.State != ConnectionState.Closed) { Connection.Close(); } Connection.Dispose(); Connection = null; } } #endregion #region 执行查询 /// /// /// /// /// public DataTable ExecQuery(string strSQL) { DataSet dsTemp = new DataSet(); try { using (MySqlDataAdapter daExcute = new MySqlDataAdapter(strSQL, GetConnection())) { daExcute.Fill(dsTemp); if (DBNull.Value.Equals(dsTemp) || dsTemp.Tables.Count < 1 || DBNull.Value.Equals(dsTemp.Tables[0])) { throw new Exception("查询结果为空."); } else { return dsTemp.Tables[0]; } } } catch (Exception ex) { throw new Exception(ex.Message, ex); } } #endregion #region 执行增删改 public int ExecuteNonQuery(string strSQL) { int result = 0; try { using (var command = new MySqlCommand(strSQL, GetConnection())) { result = command.ExecuteNonQuery(); // 执行命令并返回受影响的行数 } } catch (Exception ex) { // 处理异常 throw new Exception(ex.Message, ex); } return result; } #endregion } }