using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace yinLouSys.code
{
    public class SQLHelp
    {
        //获取连接字符串(从web.config获取连接字符串)
        private static String connStr = ConfigurationSettings.AppSettings["connectionString"];

        private static int _runC = 0;

        //事务开启标志
        private static bool isTransaction = false;

        //事务处理对象
        private static SqlTransaction objSqlTransaction;

        //执行SQL命令的对象
        private static SqlCommand dbCommand;

        //数据库连接对象
        private static SqlConnection dbConnection;

        //防止实例化
        private SQLHelp() { }


        //从外部传入连接字符串
        public static string SetConnectionStr
        {
            set { connStr = value; }
            get
            {
                string my = ConfigurationSettings.AppSettings["passwordKey"];
                if (my != null && _runC == 0)
                {
                    connStr = Base.Decrypt(connStr, my);
                    _runC++;
                }
                return connStr;
            }
        }

        /// <summary>
        /// 判断事务是否开启
        /// </summary>
        public static bool IsTransaction
        {
            get { return isTransaction; }
        }

        /// <summary>
        /// 执行返回第一行第一列的SQL语句(返回int型)
        /// </summary>
        /// <param name="sql">要执行的存储过程名或SQL语句</param>
        /// <param name="parms">参数列表</param>
        /// <returns></returns>
        public static int ExecuteScalarCommonByInt(String sql, SqlParameter[] parms, CommandType type)
        {
            SqlConnection con = new SqlConnection(SetConnectionStr);
            try
            {
                con.Open();
                SqlCommand dbCommand = new SqlCommand(sql, con);
                dbCommand.Parameters.Clear();
                dbCommand.Connection = con;
                dbCommand.CommandText = sql;
                dbCommand.CommandType = type;

                if (parms != null)
                {
                    for (int i = 0; i < parms.Length; i++)
                    {
                        dbCommand.Parameters.Add(parms[i]);
                    }
                }
                object obj = dbCommand.ExecuteScalar();

                if (obj is DBNull)
                {
                    throw new Exception("没有查找到相应数据!");
                }

                return (int)obj;
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [ExecuteScalarCommonByInt()] 时出错:" + ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }

        #region 执行一组的SQL语句(常向阳在2012年3月24日添加)
        /// <summary>
        /// 执行一组的SQL语句
        /// </summary>
        /// <returns></returns>
        public static bool ExecuteByGroup(object[] sqls)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            connObj.Open();
            SqlTransaction tran = connObj.BeginTransaction();
            string sql = "";
            int count = 0;
            bool isSuccess = true;
            try
            {
                SqlCommand cmdObj = new SqlCommand();
                cmdObj.Transaction = tran;
                cmdObj.Connection = connObj;

                for (int i = 0; i < sqls.Length; i++)
                {
                    sql = sqls[i].ToString();
                    cmdObj.CommandText = sqls[i].ToString();
                    count = cmdObj.ExecuteNonQuery();
                    if (count <= 0)
                    {
                        isSuccess = false;
                        break;
                    }
                }
                if (isSuccess)
                {
                    tran.Commit();
                    return true;

                }
                else
                {
                    tran.Rollback();
                    return false;
                }
            }
            catch (SqlException ex)
            {
                tran.Rollback();
                throw new Exception("执行 [ExecuteScalarByInt()] SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
            finally
            {
                connObj.Close();
                connObj.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 执行SQL查询语句并返回数据集
        /// </summary>
        /// <param name="sql">要执行的SQL语句</param>
        /// <param name="tabName">表名</param>
        /// <returns></returns>
        public static DataTable ExecuteDataTable(String sql)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            try
            {
                SqlCommand dbCommand = new SqlCommand(sql, connObj);
                DataSet ds = new DataSet();
                ds.Clear();
                dbCommand.Connection = connObj;
                dbCommand.CommandType = System.Data.CommandType.Text;
                dbCommand.CommandText = sql;
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = dbCommand;
                adapter.Fill(ds, "aa1");

                DataTable bbb = new DataTable("aa1");
                bbb = ds.Tables["aa1"];
                ds.Tables.Clear();
                return bbb;
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [ExecuteDataTable()]SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
        }

        /// <summary>
        /// 获取一个可用的连接
        /// </summary>
        /// <returns></returns>
        public static SqlConnection GetConnection()
        {

            try
            {
                dbConnection = new SqlConnection(SetConnectionStr);
                dbCommand = new SqlCommand();

                if (dbConnection.State != ConnectionState.Open)
                {
                    dbConnection.Open();
                }
                return dbConnection;
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [GetConnection()] 时出错:" + ex.Message);
            }
        }


        /// <summary>
        /// 开启事务
        /// </summary>
        public static void StartTransaction()
        {
            GetConnection();
            objSqlTransaction = dbConnection.BeginTransaction();
            dbCommand.Transaction = objSqlTransaction;
            isTransaction = true;
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public static void CommitTransaction()
        {
            objSqlTransaction.Commit();
            isTransaction = false;

        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public static void BackTransacton()
        {
            if (isTransaction)
            {
                objSqlTransaction.Rollback();
                isTransaction = false;
            }
            Dispose();
        }

        /// <summary>
        /// 执行SQL查询语句并返回数据读取器
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteDataReader(String sql)
        {
            SqlConnection con = new SqlConnection(SetConnectionStr);
            try
            {
                con.Open();
                SqlCommand comm = new SqlCommand(sql, con);
                return comm.ExecuteReader();
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [ExecuteDataReader()]SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
        }




        /// <summary>
        /// 执行SQL查询语句并返回第一行第一列的值
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static object ExecuteScalar(String sql, SqlParameter[] parms)
        {
            SqlConnection con = new SqlConnection(SetConnectionStr);
            try
            {
                //GetConnection();
                con.Open();
                SqlCommand dbCommand = new SqlCommand(sql, con);
                if (parms != null)
                {
                    for (int i = 0; i < parms.Length; i++)
                    {
                        dbCommand.Parameters.Add(parms[i]);
                    }
                }
                object obj = dbCommand.ExecuteScalar();

                dbCommand.Dispose();
                if (obj is DBNull)
                {
                    return null;
                }

                return obj;
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [ExecuteScalar()] SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }

        /// <summary>
        /// 执行返回第一行第一列的SQL语句(返回int型)
        /// </summary>
        /// <param name="sql">要执行的SQL语句</param>
        /// <param name="parms">参数列表</param>
        /// <returns></returns>
        public static int ExecuteScalarByInt(String sql, SqlParameter[] parms)
        {
            SqlConnection con = new SqlConnection(SetConnectionStr);
            try
            {

                con.Open();
                SqlCommand dbCommand = new SqlCommand(sql, con);
                if (parms != null)
                {
                    for (int i = 0; i < parms.Length; i++)
                    {
                        dbCommand.Parameters.Add(parms[i]);
                    }
                }
                object obj = dbCommand.ExecuteScalar();

                if (obj is DBNull)
                {
                    throw new Exception("没有查找到相应数据!");
                }

                return (int)obj;
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [ExecuteScalarByInt()]SQL语句(" + sql + ")  时出错:" + ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }

        /// <summary>
        /// 执行一组无返回值的SQL语句
        /// </summary>
        /// <param name="sqls"></param>
        public static void ExecuteSingleValueByGroup(object[] sqls)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            connObj.Open();
            SqlTransaction tran = connObj.BeginTransaction();
            string sql = "";
            try
            {
                SqlCommand cmdObj = new SqlCommand();
                cmdObj.Transaction = tran;
                cmdObj.Connection = connObj;

                for (int i = 0; i < sqls.Length; i++)
                {
                    sql = sqls[i].ToString();
                    cmdObj.CommandText = sqls[i].ToString();
                    cmdObj.ExecuteNonQuery();
                }
                tran.Commit();
            }
            catch (SqlException ex)
            {
                tran.Rollback();
                throw new Exception("执行 [ExecuteScalarByInt()] SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
            finally
            {
                connObj.Close();
                connObj.Dispose();
            }


        }


        /// <summary>
        /// 执行SQL查询语句并返回数据集
        /// </summary>
        /// <param name="sql">要执行的SQL语句</param>
        /// <returns></returns>
        public static DataSet ExecuteDataSet(String sql)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            try
            {

                SqlCommand dbCommand = new SqlCommand(sql, connObj);
                DataSet ds = new DataSet();
                dbCommand.Connection = connObj;
                dbCommand.CommandType = System.Data.CommandType.Text;
                dbCommand.CommandText = sql;
                dbCommand.CommandTimeout = 150;
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = dbCommand;
                adapter.Fill(ds);
                return ds;
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [ExecuteDataSet()]SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
        }


        /// <summary>
        /// 执行SQL查询语句并返回数据集
        /// </summary>
        /// <param name="sql">要执行的SQL语句</param>
        /// <param name="tabName">表名</param>
        /// <returns></returns>
        public static DataTable ExecuteDataTable(String sql, String tabName)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            try
            {
                SqlCommand dbCommand = new SqlCommand(sql, connObj);
                DataSet ds = new DataSet();
                ds.Clear();
                dbCommand.Connection = connObj;
                dbCommand.CommandType = System.Data.CommandType.Text;
                dbCommand.CommandText = sql;
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = dbCommand;
                adapter.Fill(ds, tabName);

                DataTable bbb = new DataTable(tabName);
                bbb = ds.Tables[tabName];
                ds.Tables.Clear();
                return bbb;
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [ExecuteDataTable()]SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
        }

        /// <summary>
        /// 执行防注入式攻击的查询方法(通用方法)
        /// </summary>
        /// <param name="sql">存储过程名或SQL语句</param>
        /// <param name="parms">参数列表</param>
        /// <param name="type">SQL语句类型</param>
        /// <returns></returns>
        public static DataSet ExecuteSQLCommon(String sql, SqlParameter[] parms, CommandType type)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            try
            {
                connObj.Open();
                SqlCommand dbCommand = new SqlCommand(sql, connObj);
                dbCommand.Parameters.Clear();
                dbCommand.Connection = connObj;
                dbCommand.CommandText = sql;
                dbCommand.CommandType = type;

                SqlDataAdapter adapter = new SqlDataAdapter(dbCommand);
                DataSet ds = new DataSet();
                if (parms != null)
                {
                    for (int i = 0; i < parms.Length; i++)
                    {
                        dbCommand.Parameters.Add(parms[i]);
                    }
                }

                adapter.Fill(ds);

                return ds;
            }
            catch (SqlException ex)
            {
                if (isTransaction)
                {
                    objSqlTransaction.Rollback();
                }
                throw new Exception("执行 [ExecuteSQLCommon()]SQL语句(" + sql + ") 时出错:" + ex.Message);
            }
            finally
            {
                connObj.Close();
                connObj.Dispose();
            }
        }

        /// <summary>
        /// 执行增、删、改操作
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExecuteNoResult(String sql)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            try
            {
                connObj.Open();
                SqlCommand dbCommand = new SqlCommand(sql, connObj);
                dbCommand.Connection = connObj;
                dbCommand.CommandText = sql;
                return dbCommand.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                if (isTransaction)
                {
                    objSqlTransaction.Rollback();
                }

                throw new Exception("执行 [ExecuteNoResult()] SQL语句(" + sql + ")时出错:" + ex.Message);
            }
            finally
            {
                connObj.Close();
                connObj.Dispose();
            }
        }

        /// <summary>
        /// 执行增、删、改操作
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExecuteNoResult(String sql, SqlParameter[] parms, CommandType type)
        {
            SqlConnection connObj = new SqlConnection(SetConnectionStr);
            try
            {
                connObj.Open();
                SqlCommand dbCommand = new SqlCommand(sql, connObj);
                dbCommand.Connection = connObj;
                dbCommand.CommandText = sql;
                dbCommand.CommandType = type;
                dbCommand.Parameters.Clear();

                if (parms != null)
                {
                    for (int i = 0; i < parms.Length; i++)
                    {
                        dbCommand.Parameters.Add(parms[i]);
                    }
                }

                return dbCommand.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                if (isTransaction)
                {
                    objSqlTransaction.Rollback();
                }

                throw new Exception("执行带参数 [ExecuteNoResult()] SQL语句(" + sql + ")时出错:" + ex.Message);
            }
            finally
            {
                connObj.Close();
                connObj.Dispose();
            }
        }

        /// <summary>
        /// 释放数据库资源
        /// </summary>
        public static void Dispose()
        {
            try
            {
                if (dbConnection != null)
                {
                    dbConnection.Close();
                    dbConnection.Dispose();
                    dbConnection = null;
                }
            }
            catch (SqlException ex)
            {
                throw new Exception("执行 [Dispose()] 时出错:" + ex.Message);
            }
        }
    }
}
