using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MOKA_Factory_Tools.Database
{
    class DbHelper
    {
        #region 公共方法		
        /// <summary>
        /// 是否存在该连接对象
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static bool IsConnectionExists(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    if (connection.State != ConnectionState.Open)
                        connection.Open();

                    connection.Close();
                    return true;
                }
                catch
                {

                }
            }

            return false;
        }

        /// <summary>
        /// 表字段是否存在;
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>
        public static bool IsColumnExists(string connectionString, string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
            object res = GetSingle(sql, connectionString);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }

        /// <summary>
        /// 表是否存在;
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static bool IsTableExists(string connectionString, string tableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N'[" + tableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            object obj = GetSingle(strsql, connectionString);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }

            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 视图是否存在
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool IsViewsExists(string connectionString, string viewsName)
        {
            try
            {
                string strsql = "SELECT count([object_id]) as objCount FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[" + viewsName + "]')";
                //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
                object obj = GetSingle(strsql, connectionString);
                int cmdresult;
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    cmdresult = 0;
                }
                else
                {
                    cmdresult = int.Parse(obj.ToString());
                }
                if (cmdresult == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {

            }

            return false;
        }

        public static int GetMaxID(string connectionString, string FieldName, string TableName, string strWhere = "")
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            if (strWhere.Trim() != "")
            {
                strsql += (" where 1=1 and  (" + strWhere + ")");
            }

            object obj = GetSingle(connectionString, strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        public static bool Exists(string connectionString, string strSQL)
        {
            int cmdresult;
            object obj = GetSingle(connectionString, strSQL);
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static bool Exists(string connectionString, string strSQL, params SqlParameter[] cmdParms)
        {
            object obj = GetSingle(connectionString, strSQL, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 获取时间为"1900-01-01"的日期对象
        /// </summary>
        /// <returns></returns>
        public static DateTime GetNullDateTime()
        {
            return Convert.ToDateTime("1900-01-01");
        }

        /// <summary>
        /// 全局ID GUID获取19位的唯一数字序列 
        /// </summary>
        /// <returns></returns>
        public static long GenerateId()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

        /// <summary>
        /// 返回指定类型是否为允许为null的 Nullable泛型对象
        /// </summary>
        /// <param name="_type"></param>
        /// <returns>是Nullable泛型对象为 true 否则为 false</returns>
        public static bool IsNullable(Type _type)
        {
            bool bl = _type.Name.ToLower().Contains("Nullable".ToLower());
            return bl;
        }

        /// <summary>
        /// 验证一个类的完全限定名中是否以“system.”开头
        /// </summary>
        /// <param name="classFullName"></param>
        /// <returns>以“system.”开头为 true 否则为 false </returns>
        public static bool VerificationClassFullNameIsSystem(string classFullName)
        {
            bool bl = false;
            if (classFullName.ToLower().IndexOf("system.") == 0)
            {
                bl = true;
            }
            return bl;
        }

        /// <summary>
        /// 获取实例对象属性的值
        /// </summary>
        /// <param name="model">实例对象</param>
        /// <param name="propertyName">属性名</param>
        /// <returns></returns>
        public static object GetPropertyValue(object model, string propertyName)
        {
            System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty(propertyName);
            if (propertyInfo != null)
            {
                object tempValue = propertyInfo.GetValue(model, null);//对应字段值

                return tempValue;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 设置实例对象属性的值
        /// </summary>
        /// <param name="model">实例对象</param>
        /// <param name="propertyInfo">属性对象</param>
        /// <param name="value">要设置的值</param>
        public static void SetPropertyValue(object model, System.Reflection.PropertyInfo propertyInfo, object value)
        {
            if (propertyInfo == null)
            {
                return;
            }

            Type tempType = propertyInfo.PropertyType;

            if (IsNullable(tempType))
            {
                tempType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
            }
            object tempValue = value;
            if (tempValue == null)
            {
                try
                {
                    propertyInfo.SetValue(model, null, null);
                }
                catch { }
            }
            else
            {

                switch (tempType.Name)
                {
                    //      空引用。
                    case "Empty":
                        propertyInfo.SetValue(model, tempValue.ToString(), null);
                        break;

                    //     常规类型，表示不会由另一个 TypeCode 显式表示的任何引用或值类型。
                    case "Object":
                        propertyInfo.SetValue(model, tempValue, null);
                        break;
                    //     数据库空（列）值。
                    case "DBNull":
                        propertyInfo.SetValue(model, null, null);
                        break;
                    //     简单类型，表示 true 或 false 的布尔值。
                    case "Boolean":
                        try
                        {
                            propertyInfo.SetValue(model, Convert.ToBoolean(tempValue), null);
                        }
                        catch
                        {
                            propertyInfo.SetValue(model, false, null);
                        }
                        break;
                    //字符
                    case "Char":
                        propertyInfo.SetValue(model, Convert.ToChar(tempValue), null);
                        break;
                    //     整型，表示值介于 -128 到 127 之间的有符号 8 位整数。
                    case "SByte":
                        propertyInfo.SetValue(model, Convert.ToSByte(tempValue), null);
                        break;
                    //     0 and 255.
                    case "Byte":
                        propertyInfo.SetValue(model, Convert.ToByte(tempValue), null);
                        break;
                    //     整型，表示值介于 -32768 到 32767 之间的有符号 16 位整数。
                    case "Int16":
                        propertyInfo.SetValue(model, Convert.ToInt16(tempValue), null);
                        break;
                    //     整型，表示值介于 0 到 65535 之间的无符号 16 位整数。
                    case "UInt16":
                        propertyInfo.SetValue(model, Convert.ToUInt16(tempValue), null);
                        break;
                    //     整型，表示值介于 -2147483648 到 2147483647 之间的有符号 32 位整数。
                    case "Int32":
                        try
                        {
                            propertyInfo.SetValue(model, Convert.ToInt32(tempValue), null);
                        }
                        catch
                        {
                            propertyInfo.SetValue(model, Convert.ToInt32(0), null);
                        }
                        break;
                    //     整型，表示值介于 0 到 4294967295 之间的无符号 32 位整数。
                    case "UInt32":
                        propertyInfo.SetValue(model, Convert.ToUInt32(tempValue), null);
                        break;
                    //     整型，表示值介于 -9223372036854775808 到 9223372036854775807 之间的有符号 64 位整数。
                    case "Int64":
                        propertyInfo.SetValue(model, Convert.ToInt64(tempValue), null);
                        break;
                    //     整型，表示值介于 0 到 18446744073709551615 之间的无符号 64 位整数。
                    case "UInt64":
                        propertyInfo.SetValue(model, Convert.ToUInt64(tempValue), null);
                        break;
                    //     浮点型，表示从大约 1.5 x 10 -45 到 3.4 x 10 38 且精度为 7 位的值。
                    case "Single":
                        propertyInfo.SetValue(model, Convert.ToSingle(tempValue), null);
                        break;
                    //     浮点型，表示从大约 5.0 x 10 -324 到 1.7 x 10 308 且精度为 15 到 16 位的值。
                    case "Double":
                        try
                        {
                            propertyInfo.SetValue(model, Convert.ToDouble(tempValue), null);
                        }
                        catch
                        {
                            propertyInfo.SetValue(model, 0, null);
                        }
                        break;
                    //     简单类型，表示从 1.0 x 10 -28 到大约 7.9 x 10 28 且有效位数为 28 到 29 位的值。
                    case "Decimal":
                        propertyInfo.SetValue(model, Convert.ToDecimal(tempValue), null);
                        break;
                    //     表示一个日期和时间值的类型。
                    case "DateTime":
                        try
                        {
                            if (tempValue != null)
                            {
                                propertyInfo.SetValue(model, Convert.ToDateTime(tempValue), null);
                            }
                        }
                        catch
                        {
                            //  propertyInfo.SetValue(model, Convert.ToDateTime("1753-01-01"), null);
                        }
                        break;
                    //     密封类类型，表示 Unicode 字符串。
                    case "String":
                        propertyInfo.SetValue(model, tempValue.ToString(), null);
                        break;
                    default:
                        string classFullName = tempType.ToString();
                        if (!VerificationClassFullNameIsSystem(classFullName))
                        {
                            try
                            {
                                Type valueType = tempType.Module.Assembly.GetType(classFullName);
                                // object obj = Activator.CreateInstance(type, null);
                                tempValue = Activator.CreateInstance(valueType, new object[] { tempValue.ToString() });
                            }
                            catch { }
                        }
                        propertyInfo.SetValue(model, tempValue, null);
                        break;
                }
            }
        }
        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSQL(string connectionString, string strSQL)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(strSQL, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="Timeouts">超时值</param>
        /// <returns></returns>
        public static int ExecuteSQLByTime(string connectionString, string strSQL, int Timeouts)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(strSQL, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Timeouts;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="listSQL">多条SQL语句</param>		
        public static int ExecuteSQLTran(string connectionString, List<String> listSQL)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < listSQL.Count; n++)
                    {
                        string strsql = listSQL[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSQL(string connectionString, string strSQL, string content)
        {
            System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
            myParameter.Value = content;

            return ExecuteSQL(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static object ExecuteSQLGet(string connectionString, string strSQL)
        {
            System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
            myParameter.Value = connectionString;

            return GetSingle(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
        }

        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSQLInsertImg(string connectionString, string strSQL, byte[] fs)
        {
            System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
            myParameter.Value = fs;
            return ExecuteSQL(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string connectionString, string strSQL)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(strSQL, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        public static DataSet Query(string connectionString, string strSQL, int Timeout)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(strSQL, connection);
                    command.SelectCommand.CommandTimeout = Timeout;
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        #endregion

        #region 执行带参数的SQL语句
        /// <summary>
        /// 获取数据库登录用户状态
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>返回 true 为启用 false 为禁用</returns>
        public static bool GetDBUserStatus(string connectionString, string userName = "sa")
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, "SELECT is_disabled FROM sys.server_principals WHERE name ='" + userName + "'", null);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return false;
                        }
                        else
                        {
                            return !Convert.ToBoolean(obj);
                        }
                    }
                    catch
                    {
                        return false;
                    }
                }
            }
        }


        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="listSQL">多条SQL语句</param>		
        /// <param name="msg"></param>
        /// <param name="backgroundWorker"></param>
        /// <param name="times"></param>
        /// <returns></returns>
        public static int ExecuteSQLTran(string connectionString, List<string> listSQL, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
        {
            //总计数器
            float sumCount = listSQL.Count;
            //当前计数器
            int currentCount = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                if (times > 0)
                {
                    cmd.CommandTimeout = times;
                }
                try
                {
                    int count = 0;
                    if (listSQL.Count > 0)
                    {
                        for (int n = 0; n < listSQL.Count; n++)
                        {
                            currentCount++;
                            string strsql = listSQL[n];
                            if (strsql.Trim().Length > 1)
                            {
                                cmd.CommandText = strsql;
                                count += cmd.ExecuteNonQuery();
                            }

                            if (backgroundWorker != null)
                            {
                                try
                                {
                                    int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
                                    backgroundWorker.ReportProgress(currentProgres);
                                }
                                catch { }
                            }
                        }
                        tx.Commit();
                        msg = "成功!";
                        return listSQL.Count;
                    }
                    else
                    {
                        msg = "失败，错误原因：脚本内容为空！";
                        return 0;
                    }
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    msg = "失败，错误原因：" + ex.Message;
                    tx.Rollback();
                    return 0;
                }
            }
        }

        /// <summary>
        /// 执行SQL脚本文件 实现数据库事务。
        /// </summary>
        /// <param name="sqlScript">SQL脚本内容</param>
        /// <param name="msg">返回执行信息</param>
        /// <returns></returns>
        public static bool ExecuteSQLScriptTextTran(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
        {
            bool bl = false;
            List<string> SQLStringList = new List<string>();
            string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            for (int i = 0; i < sqlArray.Length; i++)
            {
                string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
                if (sql.Trim() != "")
                {
                    SQLStringList.Add(sql);
                }

            }
            int ret = ExecuteSQLTran(connectionString, SQLStringList, ref msg, backgroundWorker, times);
            if (ret > 0)
            {
                bl = true;
            }
            return bl;
        }

        /// <summary>
        /// 执行SQL脚本文件 实现数据库事务。
        /// </summary>
        /// <param name="sqlScriptFilePath">SQL脚本文件路径</param>
        /// <param name="msg">返回执行信息</param>
        /// <returns></returns>
        public static bool ExecuteSQLScriptFileTran(string connectionString, string sqlScriptFilePath, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
        {
            if (System.IO.File.Exists(sqlScriptFilePath))
            {
                string upgradeDatabaseSql = System.IO.File.ReadAllText(sqlScriptFilePath, System.Text.Encoding.UTF8);
                return ExecuteSQLScriptTextTran(connectionString, upgradeDatabaseSql, ref msg, backgroundWorker, times);
            }
            else
            {
                msg = "要执行的SQL脚本文件不存在！";
                return false;
            }
        }

        /// <summary>
        /// 执行SQL脚本文件
        /// </summary>
        /// <param name="sqlScript">SQL脚本内容</param>
        /// <param name="msg">返回执行信息</param>
        /// <returns></returns>
        public static bool ExecuteSQLScriptFile(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
        {
            bool bl = false;
            string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //总计数器
            float sumCount = sqlArray.Length;
            //当前计数器
            int currentCount = 0;
            for (int i = 0; i < sqlArray.Length; i++)
            {
                currentCount++;
                string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
                if (sql.Trim() != "")
                {
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                    try
                    {
                        List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
                        System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
                        if (times > 0)
                        {
                            ExecuteSQL(connectionString, sql, times, parameters);
                        }
                        else
                        {
                            ExecuteSQL(sql, connectionString, parameters);
                        }
                        msg = "成功!";
                        bl = true;
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        msg = "失败，错误原因：" + ex.Message;
                        bl = false;
                        break;
                    }
                }
                if (backgroundWorker != null)
                {
                    try
                    {
                        int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
                        backgroundWorker.ReportProgress(currentProgres);
                    }
                    catch { }
                }
            }
            return bl;
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSQL(string connectionString, string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSQL(string connectionString, string SQLString, int times, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        cmd.CommandTimeout = times;
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="strSQL">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static Object GetSingle(string connectionString, string strSQL)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(strSQL, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        public static Object GetSingle(string strSQL, SqlConnection connection)
        {
            using (SqlCommand cmd = new SqlCommand(strSQL, connection))
            {
                try
                {
                    if (connection.State != ConnectionState.Open)
                        connection.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    connection.Close();
                    throw e;
                }
            }
        }

        public static object GetSingle(string connectionString, string strSQL, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, strSQL, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        public static object GetSingle(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                try
                {
                    if (connection.State != ConnectionState.Open) connection.Open();
                    PrepareCommand(cmd, connection, null, strSQL, cmdParms);
                    object obj = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    throw e;
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader ( 注意：调用该方法后，一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string connectionString, string strSQL, params SqlParameter[] cmdParms)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, strSQL, cmdParms);
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
        }

        public static SqlDataReader ExecuteReader(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
        {
            if (connection.State != ConnectionState.Open) connection.Open();
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, strSQL, cmdParms);
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet MasterQuery(string connectionString, string strSQL, params SqlParameter[] cmdParms)
        {
            return Query(strSQL, connectionString, cmdParms);
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string connectionString, string strSQL, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, strSQL, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }

                    return ds;
                }
            }
        }

        public static DataSet Query(SqlConnection connection, string strSQL, params SqlParameter[] cmdParms)
        {
            if (connection.State != ConnectionState.Open) connection.Open();
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, strSQL, cmdParms);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();
                try
                {
                    da.Fill(ds, "ds");
                    cmd.Parameters.Clear();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }

                return ds;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string connectionString, string strSQL, int times, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandTimeout = times;
                PrepareCommand(cmd, connection, null, strSQL, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }

                    return ds;
                }
            }
        }

        public static DataSet Query(string strSQL, int times, SqlConnection connection, params SqlParameter[] cmdParms)
        {
            if (connection.State != ConnectionState.Open) connection.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = times;
            PrepareCommand(cmd, connection, null, strSQL, cmdParms);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();
                try
                {
                    da.Fill(ds, "ds");
                    cmd.Parameters.Clear();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }

                return ds;
            }
        }

        public static void PublicPrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
        }

        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 存储过程操作
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                return dataSet;
            }
        }

        public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.SelectCommand.CommandTimeout = Times;
                sqlDA.Fill(dataSet, tableName);
                return dataSet;
            }
        }

        /// <summary>
        /// 执行存储过程，返回影响的行数		
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                int result;
                connection.Open();
                SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                rowsAffected = command.ExecuteNonQuery();
                result = (int)command.Parameters["ReturnValue"].Value;
                return result;
            }
        }

        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)	
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }

        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }
        #endregion
    }
}
