using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; namespace GuangFu.StringTracing.Common { 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 执行增删改(不带参数) /// /// 执行增删改操作 /// /// SQL语句 /// 受影响的行数 public int ExecNonQuery(string strSQL) { try { using (MySqlCommand cmd = new MySqlCommand(strSQL, GetConnection())) { return cmd.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception("执行SQL失败: " + strSQL + "\r\n" + ex.Message, ex); } } #endregion #region 执行增删改(带参数) /// /// 执行带参数的增删改操作 /// /// SQL语句 /// 参数数组 /// 受影响的行数 public int ExecNonQuery(string strSQL, params MySqlParameter[] parameters) { try { using (MySqlCommand cmd = new MySqlCommand(strSQL, GetConnection())) { if (parameters != null && parameters.Length > 0) { cmd.Parameters.AddRange(parameters); } return cmd.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception("执行SQL失败: " + strSQL + "\r\n" + ex.Message, ex); } } #endregion } }