//--------------------------日期:2014-2-22
//--------------------------版本:1.0.0.0
//--------------------------作者:itrycn
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using SQLClient = MySql.Data.MySqlClient;
using System.ComponentModel;
namespace ryCommonDb
{
    /// <summary>
    /// 
    /// </summary>
   public class ClsMySQLDb : IDisposable
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="errorStr"></param>
        /// <param name="errorId"></param>
        public delegate void ErrorHandler(object sender, string errorStr,string errorId);
        /// <summary>
        /// 
        /// </summary>
        [Description("发生错误时发生")]
        public event ErrorHandler OnError;
        /// <summary>
        /// 
        /// </summary>
        public SQLClient.MySqlConnection SQL_cn;
        /// <summary>
        /// 
        /// </summary>
        public string fv_ConnStr = "";
        /// <summary>
        /// 
        /// </summary>
        public ClsMySQLDb()
        {
        }
        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <param name="ConnStr">数据库连接字符串</param>
        /// <returns></returns>
        public ClsMySQLDb(string ConnStr)
        {
            fv_ConnStr = ConnStr;
        }
        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <param name="DataSource">数据源</param>
        /// <param name="DbName">数据库名称</param>
        /// <param name="uId">用户id</param>
        /// <param name="pwd">用户密码</param>
        public ClsMySQLDb(string DataSource, string DbName, string uId, string pwd)
        {
            if (uId == "")
            {
                fv_ConnStr = "Data Source=" + DataSource + ";database=" + DbName + ";Integrated Security=True;Pooling=False";
            }
            else
            {
                fv_ConnStr = "Data Source=" + DataSource + ";database=" + DbName + ";uid=" + uId + ";pwd=" + pwd;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        ~ClsMySQLDb()
        {
            CloseDb();
        }
        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <returns></returns>
        public int ConnDb()
        {
            try
            {
                SQL_cn = new SQLClient.MySqlConnection
                {
                    ConnectionString = fv_ConnStr
                };
                SQL_cn.Open();
                return 1;
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return -1;
            }
        }
        /// <summary>
        /// 关闭数据库
        /// </summary>
        /// <returns></returns>
        public void CloseDb()
        {
            try
            {
                if (SQL_cn != null && SQL_cn.State != ConnectionState.Closed)
                {
                    SQL_cn.Close();
                }
            }
            catch
            {
                OnError?.Invoke(this, "关闭数据库出错", "errorclose");
            }
        }
        /// <summary>
        /// 运行SQL命令
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <returns>运行失败，则返回-1，否则返回影响的行数</returns>
        public int ExecuteNonQuery(string SQLText, SQLClient.MySqlParameter[] commandParameters)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    if (commandParameters.Length > 0)
                    {
                        foreach (SQLClient.MySqlParameter parm in commandParameters)
                        { cm.Parameters.Add(parm); }
                    }
                    cm.Connection = SQL_cn;
                    int i = cm.ExecuteNonQuery();
                    cm.Dispose();
                    return i;
                }
                #endregion
            }
            catch (Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return -1;
            }
        }
        /// <summary>
        /// 运行SQL命令
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <returns>运行失败，则返回-1，否则返回影响的行数</returns>
        public int ExecuteNonQuery(string SQLText)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    cm.Connection = SQL_cn;
                    int i = cm.ExecuteNonQuery();
                    cm.Dispose();
                    return i;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errrorconn");
                return -1;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <returns>运行失败，则返回null，否则返回以数组显示的字符串</returns>
        public string[] ExecuteSQL(string SQLText, SQLClient.MySqlParameter[] commandParameters)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    if (commandParameters.Length > 0)
                    {
                        cm.Parameters.AddRange(commandParameters);
                    }
                    SQLClient.MySqlDataReader reader = cm.ExecuteReader();
                    string[] resultStr = null;
                    while (reader.Read())
                    {
                        resultStr = new string[reader.FieldCount];
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            resultStr[i] = reader[i].ToString();
                        }
                        break;
                    }
                    reader.Close();
                    cm.Dispose();
                    return resultStr;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return null;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <param name="DefFristValue">数组第一个默认的值</param>
        /// <returns>运行失败，则返回null，否则返回以数组显示的字符串</returns>
        public string[] ExecuteSQL(string SQLText, SQLClient.MySqlParameter[] commandParameters, string DefFristValue)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    if (commandParameters.Length > 0)
                    {
                        cm.Parameters.AddRange(commandParameters);
                    }
                    SQLClient.MySqlDataReader reader = cm.ExecuteReader();
                    string[] resultStr = null;
                    while (reader.Read())
                    {
                        resultStr = new string[reader.FieldCount];
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            resultStr[i] = reader[i].ToString();
                        }
                        break;
                    }
                    if (resultStr == null)
                    {
                        resultStr = new string[1];
                        resultStr[0] = DefFristValue;
                    }
                    cm.Parameters.Clear();
                    reader.Close();
                    cm.Dispose();
                    return resultStr;
                }
                #endregion
            }
            catch(Exception ex)
            {
                string[] resultStr = null;
                resultStr = new string[1];
                resultStr[0] = DefFristValue;
                OnError?.Invoke(this, ex.Message, "errorconn");
                return resultStr;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <returns>运行失败，则返回null，否则返回以数组显示的字符串</returns>
        public string[] ExecuteSQL(string SQLText)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    SQLClient.MySqlDataReader reader = cm.ExecuteReader();
                    string[] resultStr = null;
                    while (reader.Read())
                    {
                        resultStr = new string[reader.FieldCount];
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            resultStr[i] = reader[i].ToString();
                        }
                        break;
                    }
                    reader.Close();
                    cm.Dispose();
                    return resultStr;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return null;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="DefFristValue">数组第一个默认的值</param>
        /// <returns>运行失败，则返回DefFristValue，否则返回以数组显示的字符串</returns>
        public string[] ExecuteSQL(string SQLText, string DefFristValue)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    SQLClient.MySqlDataReader reader = cm.ExecuteReader();
                    string[] resultStr = null;
                    while (reader.Read())
                    {
                        resultStr = new string[reader.FieldCount];
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            resultStr[i] = reader[i].ToString();
                        }
                        break;
                    }
                    reader.Close();
                    cm.Dispose();
                    if (resultStr == null)
                    {
                        resultStr = new string[1];
                        resultStr[0] = DefFristValue;
                    }
                    return resultStr;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                string[] resultStr = null;
                resultStr = new string[1];
                resultStr[0] = DefFristValue;
                return resultStr;
            }
        }
        /// <summary>
        /// 清空指定表的所有数据
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>运行失败，则返回-1，否则返回影响的行数</returns>
        public int ClearTableData(string TableName)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = "delete from " + TableName;
                    cm.Connection = SQL_cn;
                    int i = cm.ExecuteNonQuery();
                    cm.Dispose();
                    return i;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return -1;
            }
        }
        /// <summary>
        /// 判断指定值是否存在
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="valueField">指定值所属字段</param>
        /// <param name="value">指定值</param>
        /// <param name="curId">当前id，如果是新增记录，请填写-1</param>
        /// <returns></returns>
        public bool IsExistValue(string TableName, string valueField, string value, int curId)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = "select * from " + TableName + " where " + valueField + "=@tvalue";
                    cm.Parameters.AddWithValue("@tvalue", DbType.String);
                    cm.Parameters["@tvalue"].Value = value;
                    SQLClient.MySqlDataReader reader = cm.ExecuteReader();
                    bool result = false;
                    while (reader.Read())
                    {
                        if (curId < 0)
                        {
                            result = true;
                        }
                        else
                        {
                            if (reader["id"].ToString() == curId.ToString())
                            {
                                result = false;
                            }
                            else
                            {
                                result = true;
                            }
                        }
                        break;
                    }

                    reader.Close();
                    cm.Dispose();
                    return result;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return false;
            }
        }
        /// <summary>
        /// 判断SQL语句是否有结果返回
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <returns>运行失败，则返回-1；存在结果，返回1；不存在结果，返回0</returns>
        public int ExecuteReadResult(string SQLText, SQLClient.MySqlParameter[] commandParameters)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    if (commandParameters.Length > 0)
                    {
                        cm.Parameters.AddRange(commandParameters);
                        //foreach (SQLiteParameter parm in commandParameters)
                        //{ cm.Parameters.Add(parm); }
                    }
                    SQLClient.MySqlDataReader reader = cm.ExecuteReader();
                    int i = 0;
                    while (reader.Read())
                    {
                        i = 1;
                        break;
                    }
                    reader.Close();
                    cm.Parameters.Clear();
                    cm.Dispose();
                    return i;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return -1;
            }
        }
        /// <summary>
        /// 判断SQL语句是否有结果返回
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <returns>运行失败，则返回-1；存在结果，返回1；不存在结果，返回0</returns>
        public int ExecuteReadResult(string SQLText)
        {
            try
            {
                #region 数据库
                {
                    SQLClient.MySqlCommand cm = SQL_cn.CreateCommand();
                    cm.Parameters.Clear();
                    cm.CommandText = SQLText;
                    SQLClient.MySqlDataReader reader = cm.ExecuteReader();
                    int i = 0;
                    while (reader.Read())
                    {
                        i = 1;
                        break;
                    }
                    reader.Close();
                    cm.Dispose();
                    return i;
                }
                #endregion
            }
            catch(Exception ex)
            {
                OnError?.Invoke(this, ex.Message, "errorconn");
                return -1;
            }
        }
        private bool disposed = false;
        /// <summary>
        /// 
        /// </summary>
        public virtual void Dispose()
        {
            if (!this.disposed)
            {
                try
                {
                    CloseDb();
                    // release scarce resource here
                }
                finally
                {
                    this.disposed = true;
                    GC.SuppressFinalize(this);
                }
            }
        }
    }
}
