SqlServer DbHelper

依然范特西╮ 提交于 2019-11-29 16:05:18
    /// <summary>
    /// 数据库通用操作类
    /// </summary>
    public abstract class DbHelper
    {
        #region " 连接字符串 "
        //连接字符串
        //public static string ConnString = ConfigurationManager.ConnectionStrings["CommonSqlConnectionString"].ConnectionString;
        public static string DefaultConnString = string.Empty;
        public const int defaultCommandTimeout = 180;
        public const int defaultdbconfig = 1;

        #endregion

        #region " GetSqlCommand "

        /// <summary>
        /// 获取初始化好的Command对象
        /// </summary>
        /// <param name="conn">Connection对象</param>
        /// <param name="cmdText">命令文本</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>初始化好的Command对象</returns>
        private static SqlCommand GetSqlCommand(SqlConnection conn, string cmdText, CommandType cmdType, SqlParameter[] parameters)
        {
            SqlCommand cmd = new SqlCommand(cmdText, conn);
            cmd.CommandType = cmdType;
            cmd.CommandTimeout = defaultCommandTimeout;
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters);
            }

            return cmd;
        }

        #endregion

        #region " ExecSqlDataSet "

        public static DataTable ExecSqlDataSet(string strSQL)
        {
            return ExecSqlDataSet(strSQL, null);
        }

        public static DataTable ExecSqlDataSet(string strSQL, SqlParameter[] parameters)
        {
            return ExecSqlDataSet(strSQL, parameters, DefaultConnString);
        }

        public static DataTable ExecSqlDataSet(string strSQL, SqlParameter[] parameters, string connStr)
        {
            if (string.IsNullOrWhiteSpace(connStr))
            {
                return new DataTable();
            }
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = GetSqlCommand(conn, strSQL, CommandType.Text, parameters);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                cmd.Dispose();
                da.Dispose();
                return ds.Tables[0];
            }
        }



        #endregion

        #region " ExecSqlNonQuerry "

        /// <summary>
        /// 执行非查询SQL语句
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <returns>受影响的行数</returns>
        public static int ExecSqlNonQuerry(string strSQL)
        {
            return ExecSqlNonQuerry(strSQL, null);
        }

        /// <summary>
        /// 执行非查询的带参数的SQL语句
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <returns>受影响的行数</returns>
        public static int ExecSqlNonQuerry(string strSQL, SqlParameter[] parameters)
        {
            return ExecSqlNonQuerry(strSQL, parameters, DefaultConnString);
        }



        public static int ExecSqlNonQuerry(string strSQL, SqlParameter[] parameters, string connStr)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = GetSqlCommand(conn, strSQL, CommandType.Text, parameters);
                cmd.CommandTimeout = 0;
                int result = cmd.ExecuteNonQuery();
                cmd.Dispose();
                return result;
            }
        }

        #endregion

        #region " ExecSqlScalar "

        /// <summary>
        /// 执行统计查询
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <returns>执行结果的第1行第1列的值</returns>
        public static object ExecSqlScalar(string strSQL)
        {
            return ExecSqlScalar(strSQL, null);
        }

        /// <summary>
        /// 执行带参数的统计查询
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>执行结果的第1行第1列的值</returns>
        public static object ExecSqlScalar(string strSQL, SqlParameter[] parameters)
        {
            return ExecSqlScalar(strSQL, parameters, DefaultConnString);
        }

        /// <summary>
        /// 执行带参数的统计查询
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>执行结果的第1行第1列的值</returns>
        public static object ExecSqlScalar(string strSQL, SqlParameter[] parameters, string connStr)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = GetSqlCommand(conn, strSQL, CommandType.Text, parameters);
                object result = cmd.ExecuteScalar();
                cmd.Dispose();
                return result;
            }
        }

        #endregion

        #region " ExecProcDataSet "

        /// <summary>
        /// 执行存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <returns>查询结果</returns>
        public static DataSet ExecProcDataSet(string procName)
        {
            return ExecProcDataSet(procName, null);
        }
        /// <summary>
        /// 执行带参数的存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>查询结果</returns>
        public static DataSet ExecProcDataSet(string procName, SqlParameter[] parameters)
        {
            return ExecProcDataSet(procName, parameters, DefaultConnString);
        }

        /// <summary>
        /// 执行带参数的存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>查询结果</returns>
        public static DataSet ExecProcDataSet(string procName, SqlParameter[] parameters, string connStr)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = GetSqlCommand(conn, procName, CommandType.StoredProcedure, parameters);
                cmd.CommandTimeout = 0;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                cmd.Dispose();
                return ds;
            }
        }


        #endregion

        #region " ExecProcDataTable "

        /// <summary>
        /// 执行存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <returns>查询结果</returns>
        public static DataTable ExecProcDataTable(string procName)
        {
            return ExecProcDataSet(procName).Tables[0];
        }
        /// <summary>
        /// 执行带参数的存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>查询结果</returns>
        public static DataTable ExecProcDataTable(string procName, SqlParameter[] parameters)
        {
            return ExecProcDataSet(procName, parameters).Tables[0];
        }

        public static DataTable ExecProcDataTable(string procName, SqlParameter[] parameters, string connStr)
        {
            return ExecProcDataSet(procName, parameters, connStr).Tables[0];
        }


        #endregion

        #region " ExecProcNonQuerry "

        /// <summary>
        /// 执行非查询存储过程
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <returns>受影响的行数</returns>
        public static int ExecProcNonQuerry(string procName)
        {
            return ExecProcNonQuerry(procName);
        }

        /// <summary>
        /// 执行非查询的带参数的存储过程
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <returns>受影响的行数</returns>
        public static int ExecProcNonQuerry(string procName, SqlParameter[] parameters)
        {
            return ExecProcNonQuerry(procName, parameters, DefaultConnString);
        }


        /// <summary>
        /// 执行非查询的带参数的存储过程
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <returns>受影响的行数</returns>
        public static int ExecProcNonQuerry(string procName, SqlParameter[] parameters, string connStr)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = GetSqlCommand(conn, procName, CommandType.StoredProcedure, parameters);
                int result = cmd.ExecuteNonQuery();
                cmd.Dispose();
                return result;
            }
        }



        #endregion

        #region " ExecSqlDataReader "

        /// <summary>
        /// 执行SQL语句,返回执行结果
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <returns>查询结果</returns>
        public static SqlDataReader ExecSqlDataReader(string strSQL)
        {
            return ExecSqlDataReader(strSQL, null);
        }

        /// <summary>
        /// 执行带参数的SQL语句,返回执行结果
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>查询结果</returns>
        public static SqlDataReader ExecSqlDataReader(string strSQL, SqlParameter[] parameters)
        {
            return ExecSqlDataReader(strSQL, parameters, DefaultConnString);
        }

        /// <summary>
        /// 执行带参数的SQL语句,返回执行结果
        /// </summary>
        /// <param name="strSQL">待执行SQL语句</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>查询结果</returns>
        public static SqlDataReader ExecSqlDataReader(string strSQL, SqlParameter[] parameters, string connStr)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = GetSqlCommand(conn, strSQL, CommandType.Text, parameters);
                SqlDataReader result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Dispose();
                return result;
            }
        }


        #endregion

        #region " ExecProcDataReader "

        /// <summary>
        /// 执行存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <returns>查询结果</returns>
        public static SqlDataReader ExecProcDataReader(string procName)
        {
            return ExecProcDataReader(procName, null);
        }

        /// <summary>
        /// 执行带参数的存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>查询结果</returns>
        public static SqlDataReader ExecProcDataReader(string procName, SqlParameter[] parameters)
        {
            return ExecProcDataReader(procName, parameters, DefaultConnString);
        }

        /// <summary>
        /// 执行带参数的存储过程,返回执行结果
        /// </summary>
        /// <param name="procName">待执行存储过程</param>
        /// <param name="parameters">参数数组</param>
        /// <returns>查询结果</returns>
        public static SqlDataReader ExecProcDataReader(string procName, SqlParameter[] parameters, string connStr)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();

                SqlCommand cmd = GetSqlCommand(conn, procName, CommandType.StoredProcedure, parameters);
                SqlDataReader result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Dispose();
                return result;
            }
        }



        #endregion

        #region " DtToSqlServer "

        /// <summary>
        /// 将DataTable批量导入SqlServer
        /// </summary>
        /// <param name="dtExcel">数据表</param>
        /// <param name="tableName">目标数据表名</param>
        /// <param name="dtColName">对应列的数据集</param>
        public static void DtToSqlServer(DataTable dtExcel, string tableName, DataTable dtColName)
        {
            DtToSqlServer(dtExcel, tableName, dtColName, DefaultConnString);
        }

        /// <summary>
        /// 将DataTable批量导入SqlServer
        /// </summary>
        /// <param name="dtExcel">数据表</param>
        /// <param name="tableName">目标数据表名</param>
        /// <param name="dtColName">对应列的数据集</param>
        public static void DtToSqlServer(DataTable dtExcel, string tableName, DataTable dtColName, string connStr)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();

                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
                {
                    try
                    {
                        bulkCopy.DestinationTableName = tableName;//要插入的表的表名
                        for (int i = 0; i < dtColName.Rows.Count; i++)
                        {
                            bulkCopy.ColumnMappings.Add(dtColName.Rows[i][0].ToString().Trim(), dtColName.Rows[i][1].ToString().Trim());

                        }

                        bulkCopy.WriteToServer(dtExcel);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }

        #endregion

        #region
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbconfig">目标连接字符</param>
        /// <param name="tablename">目标表</param>
        /// <param name="dt">源数据</param>
        public static string SqlBulkCopyByDatatable(string tablename, DataTable table, string connStr, SqlConnection m_clsSqlConn)
        {
            string dataBaseStr = "";
            if (tablename.Contains("."))
            {
                dataBaseStr = tablename.Substring(0, tablename.LastIndexOf(".") + 1);
                tablename = tablename.Substring(tablename.LastIndexOf(".") + 1);
            }

            try
            {
                string result = "";
                SqlBulkCopy sqlBulkCopy = null;
                if (m_clsSqlConn != null)
                {
                    sqlBulkCopy = new SqlBulkCopy(m_clsSqlConn);
                    if (m_clsSqlConn.State == ConnectionState.Closed)
                    {
                        m_clsSqlConn.Open();
                    }
                }
                else
                {
                    sqlBulkCopy = new SqlBulkCopy(connStr);
                }

                

                sqlBulkCopy.DestinationTableName = dataBaseStr + ((tablename.IndexOf("[") > -1 && tablename.IndexOf("]") > -1) ? tablename : "[" + tablename + "]");
                sqlBulkCopy.BulkCopyTimeout = 500;
                //sqlBulkCopy.BatchSize = 800;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    sqlBulkCopy.ColumnMappings.Add(table.Columns[i].ColumnName, table.Columns[i].ColumnName);
                }

                if (table.Rows.Count > 0)
                {
                    sqlBulkCopy.WriteToServer(table);
                }
                else
                {
                    result = "表为空";
                }

                sqlBulkCopy.Close();
                return result;
            }
            catch (Exception e)
            {
                return e.Message;
            }
            finally
            {
                try
                {
                    if (m_clsSqlConn != null)
                    {

                        try
                        {
                            if (m_clsSqlConn.State == ConnectionState.Open)
                            {
                                m_clsSqlConn.Close();
                            }
                        }
                        catch (Exception)
                        {

                        }
                    }
                }
                catch (Exception)
                {

                }
            }
        }

        public static string SqlBulkCopyByDatatable(string tablename, DataTable table, SqlConnection m_clsSqlConn)
        {
            return SqlBulkCopyByDatatable(tablename, table, string.Empty, m_clsSqlConn);

        }
        public static string SqlBulkCopyByDatatable(string tablename, DataTable table, string connStr)
        {
            return SqlBulkCopyByDatatable(tablename, table, connStr, null);
        }

        public static string SqlBulkCopyByDatatable(string tablename, DataTable table)
        {
            return SqlBulkCopyByDatatable(tablename, table, DefaultConnString, null);
        }

        public static string CreateTempTable(string tablename, DataTable table, string connStr)
        {
            return CreateTempTable(tablename, table, new SqlConnection(connStr));
        }
        public static string CreateTempTable(string tablename, DataTable table, SqlConnection connStr)
        {
            try
            {

                string sqlstr = "CREATE TABLE [" + tablename + "](";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    switch (table.Columns[i].DataType.FullName)
                    {
                        case "System.String":
                            {
                                sqlstr += "[" + table.Columns[i].ColumnName + "] [nvarchar](4000) NULL,";
                            }
                            break;
                        case "System.Int32":
                            {
                                sqlstr += "[" + table.Columns[i].ColumnName + "] [int] NULL,";
                            }
                            break;
                        case "System.Double":
                            {
                                sqlstr += "[" + table.Columns[i].ColumnName + "] [numeric](24,2) NULL,";
                            }
                            break;
                        case "System.DateTime":
                            {
                                sqlstr += "[" + table.Columns[i].ColumnName + "] [datetime] NULL,";
                            }
                            break;
                        default:
                            {
                                sqlstr += "[" + table.Columns[i].ColumnName + "] [nvarchar](4000) NULL,";
                            }
                            break;
                    }
                }
                sqlstr = sqlstr.Substring(0, sqlstr.Length - 1) + ")";

                if (connStr.State != ConnectionState.Open)
                {
                    connStr.Open();
                }

                SqlCommand cmd = GetSqlCommand(connStr, sqlstr, CommandType.Text, null);
                int result = cmd.ExecuteNonQuery();
                cmd.Dispose();
                return "";
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

        #endregion


    }

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!