using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
namespace Sky.Darkness.Commons.DataAccess
{
    #region DBHelper类，提供数据库连接SqlConnection
    /// <summary>
    /// 数据库连接类
    /// Initialize the data access layer by
    /// loading the database connection string from 
    /// the Web.Config file
    /// </summary>
    public abstract class DBHelper
    {
        private static string _connectionString = string.Empty;
        private static SqlConnection _sqlConnection = null;

        public static SqlConnection GetConnection()
        {
            if ("".Equals(_connectionString))
                _connectionString = ConfigurationManager.AppSettings["GlobalConnectionString"];

            if (string.IsNullOrEmpty(_connectionString))
                throw new Exception("No connection string configured in Web.Config file");

            if (_sqlConnection == null)
                _sqlConnection = new SqlConnection(_connectionString);

            if (_sqlConnection.State == ConnectionState.Closed)
                _sqlConnection.Open();

            return _sqlConnection;
        }
    }
    #endregion DBHelper类，提供数据库连接SqlConnection

    #region SqlHelper类，数据库操作帮助类
    /// <summary>
    /// SqlHelper 的摘要说明 
    /// 数据库操作类
    /// </summary>
    public class SqlHelper : DBHelper
    {
        #region 返回json格式数据，因考虑前期项目兼容性，临时存放此处，后期会转移到别处
        public static string ExecuteSqlReader(string strSql)
        {
            string json = "";

            // Create command
            SqlCommand cmd = null;

            // Add parameters
            // cmd.Parameters.AddWithValue("@TeacherID", teacherID);

            // Execute command
            try
            {
                cmd = CreateSqlCommand(strSql);
                SqlDataReader reader = cmd.ExecuteReader();

                json = "[";
                while (reader.Read())
                {
                    string nodeId = reader["nodeId"].ToString();
                    string title = reader["title"].ToString();
                    string leaf = reader["leaf"].ToString().ToLower();

                    json += "{id:'" + nodeId + "',";
                    json += "text:'" + title + "',";
                    json += "leaf:" + leaf + "},";
                }
                json = json.Substring(0, json.Length - 1);
                json += "]";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Connection.Close();
                cmd.Dispose();
            }

            return json;
        }
        #endregion

        #region ExecuteScalar>>object，根据CommandText查询出首行首列数据,CommandType默认为CommandType.Text
        public static object ExecuteScalar(string commandText)
        {
            return ExecuteScalar(commandText,null,CommandType.Text);
        }
        #endregion 

        #region ExecuteScalar>>object，根据CommandText、SqlParameter[]、CommandType查询出首行首列数据
        public static object ExecuteScalar(string commandText, SqlParameter[] para, CommandType commandType)
        {
            SqlCommand cmd = null;
            try
            {
                cmd = CreateSqlCommand(commandText, para, commandType);
                return cmd.ExecuteScalar();//返回首行首列
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                try
                {
                    cmd.Connection.Close();
                    cmd.Dispose();
                }
                catch
                {
                }
            }
        }
        #endregion

        #region CreateSqlCommand>>SqlCommand,根据CommandText来创建SlqCommand对象，数据库连接默认,CommandType默认为CommandType.Text
        /// <summary>
        /// 创建SlqCommand对象
        /// </summary>
        /// <param name="commandText">string命令文本</param>
        /// <param name="para">SqlParameter[]参数</param>
        /// <param name="commandType">CommandType命令类型</param>
        /// <returns></returns>
        public static SqlCommand CreateSqlCommand(string commandText)
        {
            return CreateSqlCommand(commandText, null, CommandType.Text);
        }
        #endregion

        #region CreateSqlCommand>>SqlCommand,根据CommandText、SqlParameter[]、CommandType来创建SlqCommand对象，数据库连接默认
        /// <summary>
        /// 创建SlqCommand对象
        /// </summary>
        /// <param name="commandText">string命令文本</param>
        /// <param name="para">SqlParameter[]参数</param>
        /// <param name="commandType">CommandType命令类型</param>
        /// <returns></returns>
        public static SqlCommand CreateSqlCommand(string commandText, SqlParameter[] para, CommandType commandType)
        {
            SqlCommand cmd = new SqlCommand(); //创建Command对象
            try
            {
                cmd.CommandType = commandType; //设置CommandType
                cmd.CommandText = commandText; //设置CommandText
                cmd.Connection = GetConnection(); //得到数据库连接
                if (para != null)
                {
                    foreach (SqlParameter sp in para)//添加存储过程参数
                    {
                        cmd.Parameters.Add(sp);
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            return cmd;
        }
        #endregion 根据CommandText、SqlParameter[]、CommandType来创建SlqCommand对象，数据库连接默认

        #region ExecuteStoredProcedure>>int,根据CommandText来执行增删改操作,CommandType默认为CommandType.StoredProcedure
        public static int ExecuteStoredProcedure(string commandText)
        {
            try
            {
                return ExecuteNonQuery(commandText, null, CommandType.StoredProcedure);
            }
            catch
            {
            }
            return -1;
        }
        #endregion

        #region ExecuteStoredProcedure>>int,根据CommandText、SqlParameter[]来执行增删改操作,CommandType默认为CommandType.StoredProcedure
        public static int ExecuteStoredProcedure(string commandText, SqlParameter[] para)
        {
            try
            {
                return ExecuteNonQuery(commandText, para, CommandType.StoredProcedure);
            }
            catch
            {
            }
            return -1;
        }
        #endregion

        #region ExecuteOutPutProc>>ArrayList,根据CommandText、SqlParameter[]来执行增删改操作，存储过程带输出参数
        /// <summary>
        /// 增删改操作，存储过程带输出参数
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="para">参数</param>
        /// <param name="commandType">命令类型</param>
        /// <returns>存储过程输出参数的值列表</returns>
        public static ArrayList ExecuteOutPutProc(string commandText, SqlParameter[] para)
        {
            ArrayList result = new ArrayList();
            ExecuteNonQuery(commandText, para, CommandType.StoredProcedure);
            foreach (SqlParameter p in para)
            {
                if (p.Direction == ParameterDirection.Output)
                {
                    result.Add(p.Value);
                }
            }
            return result;
        }
        #endregion

        #region ExecuteNonQuery>>int,根据CommandText来执行增删改操作,CommandType默认为CommandType.Text
        public static int ExecuteNonQuery(string commandText)
        {
            try
            {
                return ExecuteNonQuery(commandText, null, CommandType.Text);
            }
            catch
            {
            }
            return -1;
        }
        #endregion

        #region ExecuteNonQuery>>int,根据CommandText、SqlParameter[]来执行增删改操作,CommandType默认为CommandType.Text
        public static int ExecuteNonQuery(string commandText, SqlParameter[] para)
        {
            try
            {
                return ExecuteNonQuery(commandText, para, CommandType.Text);
            }
            catch
            {
            }
            return -1;
        }
        #endregion

        #region ExecuteNonQuery>>int,根据CommandText、SqlParameter[]、CommandType来执行增删改操作
        /// <summary>
        /// 增删改操作
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="para">参数</param>
        /// <param name="commandType">命令类型</param>
        /// <returns>影响行数</returns>
        public static int ExecuteNonQuery(string commandText, SqlParameter[] para, CommandType commandType)
        {
            SqlCommand cmd = null;
            try
            {
                //得到SqlCommand对象
                cmd = CreateSqlCommand(commandText, para, commandType);
                return cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                try
                {
                    cmd.Connection.Close();
                    cmd.Dispose();
                }
                catch
                {
                }
            }
        }
        #endregion

        #region FillDataSet>>DataSet，根据CommandText查询DataSet,CommandType默认为CommandType.Text
        /// <summary>
        /// 查询DataSet
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="para">参数</param>
        /// <param name="commandType">命令类型</param>
        /// <returns>DataSet</returns>
        public static DataSet FillDataSet(string commandText)
        {
            return FillDataSet(commandText, null, CommandType.Text);
        }
        #endregion

        #region FillDataSet>>DataSet，根据CommandText、SqlParameter[]查询DataSet,CommandType默认为CommandType.Text
        /// <summary>
        /// 查询DataSet
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="para">参数</param>
        /// <param name="commandType">命令类型</param>
        /// <returns>DataSet</returns>
        public static DataSet FillDataSet(string commandText, SqlParameter[] para)
        {
            return FillDataSet(commandText, para, CommandType.Text);
        }
        #endregion

        #region FillDataSetByProc>>DataSet，根据CommandText、SqlParameter[]查询DataSet,CommandType默认为CommandType.StoredProcedure
        /// <summary>
        /// 查询DataSet
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="para">参数</param>
        /// <param name="commandType">命令类型</param>
        /// <returns>DataSet</returns>
        public static DataSet FillDataSetByProc(string commandText, SqlParameter[] para)
        {
            return FillDataSet(commandText, para, CommandType.StoredProcedure);
        }
        #endregion

        #region FillDataSetByProc>>DataSet，根据CommandText查询DataSet,CommandType默认为CommandType.StoredProcedure
        /// <summary>
        /// 查询DataSet
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="para">参数</param>
        /// <param name="commandType">命令类型</param>
        /// <returns>DataSet</returns>
        public static DataSet FillDataSetByProc(string commandText)
        {
            return FillDataSet(commandText, null, CommandType.StoredProcedure);
        }
        #endregion

        #region FillDataSet>>DataSet，根据CommandText、SqlParameter[]、CommandType查询DataSet
        /// <summary>
        /// 查询DataSet
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="para">参数</param>
        /// <param name="commandType">命令类型</param>
        /// <returns>DataSet</returns>
        public static DataSet FillDataSet(string commandText, SqlParameter[] para, CommandType commandType)
        {
            SqlCommand cmd = null;
            try
            {
                //得到SqlCommand对象
                cmd = CreateSqlCommand(commandText, para, commandType);
            
                //create the DataAdapter & DataSet
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();

                //fill the DataSet using default values for DataTable names, etc.
                da.Fill(ds);

                // detach the SqlParameters from the command object, so they can be used again.			
                cmd.Parameters.Clear();

                //return the dataset
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                try
                {
                    cmd.Connection.Close();
                    cmd.Dispose();
                }
                catch
                {
                }
            }
        }
        #endregion
    }
    #endregion
}