zoukankan      html  css  js  c++  java
  • SQL Server SQLHelper帮助类

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DAL
    {
        /// <summary>
        /// 针对SQLServer数据库的通用访问类
        /// </summary>
        public class SQLHelper
        {
    
            //封装数据库连接字符串
            private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();
    
            #region 封装格式化SQL语句执行的各种方法
    
            public static int Update(string sql)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    return cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    //将异常信息写入日志
                    //WriteLog(ex.Message);
                    //throw new Exception("调用public static int Update(string sql)方法时发生错:" + ex.Message);
                    string errorInfo = "调用public static int Update(string sql)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    conn.Close();
                }
            }
            public static object GetSingleResult(string sql)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    return cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    //将异常信息写入日志             
                    string errorInfo = "调用public static object  GetSingleResult(string sql)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    conn.Close();
                }
            }
            public static SqlDataReader GetReader(string sql)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch (Exception ex)
                {
                    conn.Close();
                    //将异常信息写入日志             
                    string errorInfo = "调用SqlDataReader GetReader(string sql)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
            }
            public static DataSet GetDataSet(string sql)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);//创建数据适配器对象
                DataSet ds = new DataSet();//创建一个内存数据集
                try
                {
                    conn.Open();
                    da.Fill(ds);//使用数据适配器填充数据集
                    return ds;
                }
                catch (Exception ex)
                {
                    //将异常信息写入日志             
                    string errorInfo = "调用  public static DataSet GetDataSet(string sql)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    conn.Close();
                }
            }
            public static bool UpdateByTran(List<string> sqlList)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    conn.Open();
                    cmd.Transaction = conn.BeginTransaction();//开启事务         
                    foreach (string sql in sqlList)
                    {
                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                    }
                    cmd.Transaction.Commit();//提交事务
                    return true;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                    {
                        cmd.Transaction.Rollback();//回滚事务
                    }
                    string errorInfo = "调用UpdateByTran(List<string> sqlList)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    if (cmd.Transaction != null)
                    {
                        cmd.Transaction = null;//清空事务
                    }
                    conn.Close();
                }
            }
    
            #endregion
    
            #region 封装带参数SQL语句执行的各种方法
    
            public static int Update(string sql, SqlParameter[] param)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    cmd.Parameters.AddRange(param);//封装参数
                    return cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    string errorInfo = "调用 public static int Update(string sql,SqlParameter[] param)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
            public static object GetSingleResult(string sql, SqlParameter[] param)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    cmd.Parameters.AddRange(param);//封装参数
                    return cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    //将异常信息写入日志             
                    string errorInfo = "调用 public static object GetSingleResult(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    conn.Close();
                }
            }
            public static SqlDataReader GetReader(string sql, SqlParameter[] param)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    cmd.Parameters.AddRange(param);//封装参数
                    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch (Exception ex)
                {
                    conn.Close();
                    //将异常信息写入日志             
                    string errorInfo = "调用 public static SqlDataReader GetReader(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
            }
            /// <summary>
            /// 启用事务提交多条带参数的SQL语句
            /// </summary>
            /// <param name="mainSql">主表SQL语句</param>
            /// <param name="mainParam">主表SQL语句对应的参数</param>
            /// <param name="detailSql">明细表SQL语句</param>
            /// <param name="detailParam">明细表SQL语句对应的参数数组集合</param>
            /// <returns>返回事务是否执行成功</returns>
            public static bool UpdateByTran(string mainSql, SqlParameter[] mainParam,
                string detailSql, List<SqlParameter[]> detailParam)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    conn.Open();
                    cmd.Transaction = conn.BeginTransaction();//开启事务
                    if (mainSql != null && mainSql.Length != 0)
                    {
                        cmd.CommandText = mainSql;
                        cmd.Parameters.AddRange(mainParam);
                        cmd.ExecuteNonQuery();
                    }
                    foreach (SqlParameter[] param in detailParam)
                    {
                        cmd.CommandText = detailSql;
                        cmd.Parameters.Clear();//必须要清除以前的参数
                        cmd.Parameters.AddRange(param);
                        cmd.ExecuteNonQuery();
                    }
                    cmd.Transaction.Commit();//提交事务
                    return true;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                    {
                        cmd.Transaction.Rollback();//回滚事务
                    }
                    string errorInfo = "调用  public static bool UpdateByTran(string mainSql, SqlParameter[] mainParam, string detailSql, List<SqlParameter[]> detailParam)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    if (cmd.Transaction != null)
                    {
                        cmd.Transaction = null;//清空事务
                    }
                    conn.Close();
                }
            }
    
            #endregion
    
            #region 封装调用存储过程执行的各种方法
    
            public static int UpdateByProcedure(string spName, SqlParameter[] param)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(spName, conn);
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;//声明当前操作是存储过程
                    cmd.Parameters.AddRange(param);//封装参数
                    return cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    string errorInfo = "调用 public static int UpdateByProcedure(string spName, SqlParameter[] param)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    conn.Close();
                }
            }
            public static object GetSingleResultByProcedure(string spName, SqlParameter[] param)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(spName, conn);
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddRange(param);//封装参数
                    return cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    //将异常信息写入日志             
                    string errorInfo = "调用 public static object GetSingleResult(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    conn.Close();
                }
            }
            public static SqlDataReader GetReaderByProcedure(string spName, SqlParameter[] param)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand(spName, conn);
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddRange(param);//封装参数
                    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch (Exception ex)
                {
                    conn.Close();
                    //将异常信息写入日志             
                    string errorInfo = "调用 public static SqlDataReader GetReader(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
            }
            /// <summary>
            /// 启用事务调用带参数的存储过程
            /// </summary>
            /// <param name="procedureName">存储过程名称</param>
            /// <param name="paramArray">存储过程参数数组集合</param>
            /// <returns>返回基于事务的存储过程调用是否成功</returns>
            public static bool UpdateByTran(string procedureName, List<SqlParameter[]> paramArray)
            {
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;//声明当前操作是调用存储过程
                    cmd.CommandText = procedureName;
                    cmd.Transaction = conn.BeginTransaction();//开启事务            
                    foreach (SqlParameter[] param in paramArray)
                    {
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddRange(param);
                        cmd.ExecuteNonQuery();
                    }
                    cmd.Transaction.Commit();//提交事务
                    return true;
                }
                catch (Exception ex)
                {
                    if (cmd.Transaction != null)
                    {
                        cmd.Transaction.Rollback();//回滚事务
                    }
                    string errorInfo = "调用 public static bool UpdateByTran(string procedureName,List<SqlParameter[]>paramArray)方法时发生错:" + ex.Message;
                    WriteLog(errorInfo);
                    throw new Exception(errorInfo);
                }
                finally
                {
                    if (cmd.Transaction != null)
                    {
                        cmd.Transaction = null;//清空事务
                    }
                    conn.Close();
                }
            }
         
       
    
    
    //此方法只支持SQL SERVER,针对大批量数据使用 

    public
    static bool ConditionBulkDeleteAndInsert(string tableName, DataTable dt,string columnName) { bool fag = true; StringBuilder sb = new StringBuilder(); if (dt != null && dt.Rows.Count > 0) { using (SqlConnection connection = new SqlConnection(connectString)) { connection.Open(); using (SqlTransaction transaction = connection.BeginTransaction()) { for (int i = 0; i < dt.Rows.Count; i++) { sb.Append($"DELETE FROM {tableName} WHERE {columnName} = {dt.Rows[i][columnName]}; "); } SqlCommand cmd = new SqlCommand(sb.ToString(), connection, transaction); cmd.ExecuteNonQuery(); using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction)) { bulkCopy.BulkCopyTimeout = 600000; bulkCopy.BatchSize = dt.Rows.Count; bulkCopy.DestinationTableName = tableName; try { foreach (DataColumn column in dt.Columns) { bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName); } bulkCopy.WriteToServer(dt); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); fag = false; LogHelper.WriteLog(typeof(BigDataManagement), ex); throw ex; } finally { connection.Close(); } } } } } return fag; }
    
    
    
    
    
    #endregion
    
            #region 其他方法
    
            private static void WriteLog(string log)
            {
                FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "sqlhelper.log", FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(DateTime.Now.ToString() + "   " + log);
                sw.Close();
                fs.Close();
            }
    
            #endregion
        }
    }
  • 相关阅读:
    DB2保存图片并读取动态显示图片
    DIV布局之position详解
    dojo之配置dojoconfig
    JAVA虚拟机内存架构
    UrlConnection的代理和返回状态码的问题
    自定义网站的icon和收藏夹图标
    DB2建库简单例子
    python学习笔记之函数(方法)
    python学习笔记之基础数据和控制
    MVC3学习:实现文章上一篇下一篇链接
  • 原文地址:https://www.cnblogs.com/victor-huang/p/8463676.html
Copyright © 2011-2022 走看看