欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » ASP.Net » 正文

热门阅读

适用于Asp.net的完整的DbHelperSQL类

创建时间:2011年11月24日 09:24  阅读次数:(13870)
分享到:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace DBUtility
{
    public abstract class DbHelperSQL
    {
        public DbHelperSQL()
        {

        }

        //获取解密后的字符串
        protected static string connectionString = new SymmetricMethod().Decrypto(ConfigurationSettings.AppSettings["connectionString"].ToString());

        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select isnull(max(" + FieldName + "),0)+1 from " + TableName;
            object obj = DbHelperSQL.GetSingle(strsql);
            if (obj == null)
            {
                return 1;

            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        public static bool Exists(string strSql)
        {
            object obj = DbHelperSQL.GetSingle(strSql);
            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;
            }
        }

        public static bool Exists(string strSql, params SqlParameter[] cmdParms)
        {
            object obj = DbHelperSQL.GetSingle(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 >
        /// 返回连接
        /// </summary >
        /// <returns ></returns >
        public static SqlConnection GetConnection()
        {
            string currentConnectionString = connectionString;
            if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.User.Identity.Name))
            {
                currentConnectionString = currentConnectionString + ";Application Name=ForegroundUserID=" + System.Web.HttpContext.Current.User.Identity.Name;
            }
            return new SqlConnection(currentConnectionString);
        }

        /// <summary >
        /// 执行SQL语句,返回影响的记录数
        /// </summary >
        /// <param name="SQLString" >SQL语句</param >
        /// <returns >影响的记录数</returns >
        public static int ExecuteSql(string SQLString)
        {
            using (SqlConnection connection = GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException E)
                    {
                        throw new Exception(E.Message);
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }

        /// <summary >
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary >
        /// <param name="SQLString" >计算查询结果语句</param >
        /// <returns >查询结果(object)</returns >
        public static object GetSingle(string SQLString)
        {
            using (SqlConnection connection = GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, 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 new Exception(e.Message);
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
        }

        public static object ExecuteScalar(string strSQL)
        {
            using (SqlConnection conn = GetConnection())
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strSQL;

                object result = cmd.ExecuteScalar();

                cmd.Parameters.Clear();
                return result;
            }
        }

        public static object ExecuteScalar(string strSQL, params SqlParameter[] paramter)
        {
            using (SqlConnection conn = GetConnection())
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strSQL;

                if (paramter != null)
                {
                    foreach (SqlParameter par in paramter)
                    {
                        cmd.Parameters.Add(par);
                    }
                }

                object result = cmd.ExecuteScalar();

                cmd.Parameters.Clear();
                return result;
            }
        }

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

        /// <summary >
        /// 获取数据集
        /// </summary >
        /// <param name="SQLString" ></param >
        /// <param name="dtname" ></param >
        /// <returns ></returns >
        public static DataSet Query(string SQLString, string dtname)
        {
            using (SqlConnection connection = GetConnection())
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, dtname);
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
                return ds;
            }
        }

        /// <summary >
        /// 
        /// </summary >
        /// <param name="SQLString" ></param >
        /// <param name="dtname" ></param >
        /// <param name="ds" ></param >
        /// <returns ></returns >
        public static DataSet Query(string SQLString, string dtname, ref DataSet ds)
        {
            using (SqlConnection connection = GetConnection())
            {
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, dtname);
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
                return ds;
            }
        }

        /// <summary >
        /// 执行SQL语句,返回影响的记录数
        /// </summary >
        /// <param name="SQLString" >SQL语句</param >
        /// <returns >影响的记录数</returns >
        public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = GetConnection())
            {
                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 new Exception(E.Message);
                    }
                    finally
                    {
                    }
                }
            }
        }

        /// <summary >
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary >
        /// <param name="SQLStringList" >SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param >
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SqlConnection conn = GetConnection())
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    object myDeValue = null;
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                            myDeValue = myDE.Value;

                            PrepareCommand(cmd, conn, trans, myDE.Key.ToString(), cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    trans.Commit();
                }
            }
        }

        public static List<int > ExecuteSqlTranRunID(IList<DictionaryEntry > SQLStringList, SqlConnection conn, SqlTransaction trans)
        {
            List<int > list = new List<int >();
            if (conn.State == ConnectionState.Closed) conn.Open();
            SqlCommand cmd = new SqlCommand();
            try
            {
                foreach (DictionaryEntry myDE in SQLStringList)
                {
                    SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                    PrepareCommand(cmd, conn, trans, myDE.Key.ToString(), cmdParms);
                    list.Add(int.Parse(cmd.ExecuteScalar().ToString()));
                    cmd.Parameters.Clear();
                }
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {

            }
            return list;
        }

        /// <summary >
        /// 执行事务,且事务中第一条Sql的返回值作为后面所有Sql最后一个参数的值
        /// </summary >
        /// <param name="SqlStringList" ></param >
        public static void ExecuteSqlTrans(List<DictionaryEntry > SqlStringList)
        {
            using (SqlConnection conn = GetConnection())
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    int identity = 0;
                    string cmdText;
                    SqlParameter[] parameter;
                    try
                    {
                        for (int i = 0; i < SqlStringList.Count; i++)
                        {
                            cmdText = SqlStringList[i].Key.ToString();
                            parameter = (SqlParameter[])SqlStringList[i].Value;
                            if (i == 0)
                            {
                                PrepareCommand(cmd, conn, trans, cmdText, parameter);
                                identity = int.Parse(cmd.ExecuteScalar().ToString());
                                cmd.Parameters.Clear();
                            }
                            else
                            {
                                if (parameter[parameter.Length - 1].Value == DBNull.Value || decimal.Parse(parameter[parameter.Length - 1].Value.ToString()) == 0)
                                {
                                    parameter[parameter.Length - 1].Value = identity;
                                }
                                PrepareCommand(cmd, conn, trans, cmdText, parameter);
                                cmd.ExecuteNonQuery();
                                cmd.Parameters.Clear();
                            }
                        }
                        trans.Commit();
                    }
                    catch (Exception e)
                    {
                        trans.Rollback();
                        throw e;
                    }
                }
            }
        }

        /// <summary >
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary >
        /// <param name="SQLStringList" >SQL语句的有序表(key为sql语句,value是该语句的SqlParameter[])</param >
        public static void ExecuteSqlTran(IList<DictionaryEntry > SQLStringList)
        {
            using (SqlConnection conn = GetConnection())
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    object myDeValue = null;
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            if (myDE.Key == null || string.IsNullOrEmpty(myDE.Key.ToString()))
                            {
                                continue;
                            }
                            else
                            {
                                string cmdText = myDE.Key.ToString();
                                SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                                myDeValue = myDE.Value;
                                PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                                int val = cmd.ExecuteNonQuery();
                                cmd.Parameters.Clear();
                            }
                        }
                        trans.Commit();

                    }
                    catch (SqlException ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }

                }

            }
        }

        /// <summary >
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary >
        /// <param name="SQLString" >计算查询结果语句</param >
        /// <returns >查询结果(object)</returns >
        public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, 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 new Exception(e.Message);
                    }
                    finally
                    {

                    }
                }
            }
        }

        /// <summary >
        /// 执行查询语句,返回DataSet
        /// </summary >
        /// <param name="SQLString" >查询语句</param >
        /// <returns >DataSet</returns >
        public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = GetConnection())
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, 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)
                    {
#if DEBUG
                        throw new Exception(ex.Message + SQLString);
#endif
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                    }
                    return ds;
                }
            }
        }

        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;
            if (cmdParms != null)
            {
                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }

                    if (parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input)
                    {
                        if (parameter.Value.ToString() == DateTime.MinValue.ToString() || parameter.Value.ToString() == int.MinValue.ToString())
                        {
                            parameter.Value = DBNull.Value;
                        }
                    }

                    cmd.Parameters.Add(parameter);
                }
            }
        }

        /// <summary >
        /// 执行存储过程
        /// </summary >
        /// <param name="storedProcName" >存储过程名</param >
        /// <returns >SqlDataReader</returns >
        public static DataSet RunProcedure(string storedProcName)
        {
            using (SqlConnection connection = GetConnection())
            {
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter();
                connection.Open();

                SqlCommand command = new SqlCommand();
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = storedProcName;
                command.Connection = connection;
                da.SelectCommand = command;

                da.Fill(ds);
                connection.Close();
                return ds;
            }
        }

        /// <summary >
        /// 执行存储过程
        /// </summary >
        /// <param name="storedProcName" >存储过程名</param >
        /// <param name="parameters" >存储过程参数</param >
        /// <param name="tableName" >DataSet结果中的表名</param >
        /// <returns >DataSet</returns >
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            try
            {
                using (SqlConnection connection = GetConnection())
                {
                    DataSet dataSet = new DataSet();
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataSet);
                    connection.Close();
                    return dataSet;
                }
            }
            catch (System.Data.SqlClient.SqlException E)
            {
                throw new Exception(E.Message);
            }
        }

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

        /// <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;
        }
    }
}
来源:
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论0条
  • 暂无任何评论,请留下您对本文章的看法,共同参入讨论!
发表评论:
留言人:
内  容:
请输入问题 23+80=? 的结果(结果是:103)
结  果: