using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace APIHelperLibrary
{
public class SqlDbHelper :IDisposable
{
#region Field

/// <summary>
/// 数据库连接字符串
/// </summary>
private string ConnString = string.Empty;
/// <summary>
/// 是否使用事务
/// </summary>
private bool bInTrans = false;
/// <summary>
/// 数据库连接对象
/// </summary>
private SqlConnection connection = null;
/// <summary>
/// 数据库操作事务处理对象
/// </summary>
private SqlTransaction transaction = null;

#endregion

#region Constructor
/// <summary>
/// 无参构造器
/// </summary>
public SqlDbHelper()
{
ConnString = "";
}

/// <summary>
/// 带一个参数构造器
/// </summary>
/// <param name="connStr">数据库连接字符串</param>
public SqlDbHelper(string connStr)
{
this.ConnString = connStr;
}

#endregion

#region SqlConnection Method

/// <summary>
/// 打开数据库连接
/// </summary>
private void OpenConn()
{
if (!bInTrans)
{
connection = new SqlConnection(this.ConnString);
}
else
{
if (connection == null)
{
connection = new SqlConnection(this.ConnString);
}
}
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}

/// <summary>
/// 关闭数据库连接
/// </summary>
private void CloseConn()
{
if (!bInTrans && null != connection)
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
connection.Dispose();
}
}
}

#endregion

#region SqlCommand Method

/// <summary>
/// 生成SqlCommand命令对象
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="lstParams">参数集合</param>
/// <param name="comType">sql语句类型</param>
/// <returns></returns>
private SqlCommand PreSqlCommand(string strSql, List<SqlParameter> lstParams = null, CommandType comType = CommandType.Text)
{
this.OpenConn();
//初始化SqlCommand
SqlCommand command = connection.CreateCommand();
command.CommandText = strSql;
command.CommandType = comType;
//清理参数
command.Parameters.Clear();
//是否使用事务
if (null != transaction && bInTrans)
{
command.Transaction = transaction;
}
if (null != lstParams && lstParams.Count > 0)
{
command.Parameters.AddRange(lstParams.ToArray());
}
return command;
}

#endregion

#region SqlTransaction Method

/// <summary>
/// 启动事务处理
/// </summary>
public void BeginTran()
{
if (!bInTrans)
{
this.OpenConn();
transaction = connection.BeginTransaction();
bInTrans = true;
}
}

/// <summary>
/// 提交事务处理
/// </summary>
public void CommitTran()
{
if (null != transaction && bInTrans)
{
transaction.Commit();
transaction.Dispose();
this.CloseConn();
bInTrans = false;
transaction = null;
}
}

/// <summary>
/// 回滚事务处理
/// </summary>
public void RollbackTran()
{
if (null != transaction && bInTrans)
{
transaction.Rollback();
transaction.Dispose();
this.CloseConn();
bInTrans = false;
transaction = null;
}
}

#endregion

#region Insert、Update、Delete Method

/// <summary>
/// 执行添加操作并返回自增长ID
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="lstParams">参数集合</param>
/// <param name="comType">sql语句类型</param>
/// <returns></returns>
public int ExecuteIdentity(string strSql, List<SqlParameter> lstParams = null, CommandType comType = CommandType.Text)
{
int rtnId = 0;
SqlCommand comm = null;
try
{
if (comType == CommandType.Text)
{
comm = PreSqlCommand(strSql + " SELECT @@IDENTITY AS ID ", lstParams, comType);
}
else
{
comm = PreSqlCommand(strSql, lstParams, comType);
}
int.TryParse(comm.ExecuteScalar().ToString(), out rtnId);
}
catch (Exception ex)
{
if (bInTrans)
{
this.RollbackTran();
}
throw ex;
}
finally
{
this.CloseConn();
}
return rtnId;
}

/// <summary>
/// 执行SQL语句并返回影响行数
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="lstParams">参数集合</param>
/// <param name="comType">sql语句类型</param>
/// <returns></returns>
public int ExecuteNonQuery(string strSql, List<SqlParameter> lstParams = null, CommandType comType = CommandType.Text)
{
int rtnValue = 0;
try
{
SqlCommand comm = PreSqlCommand(strSql, lstParams, comType);
rtnValue = comm.ExecuteNonQuery();
}
catch (Exception ex)
{
if (bInTrans)
{
this.RollbackTran();
}
throw ex;
}
finally
{
this.CloseConn();
}
return rtnValue;
}

/// <summary>
/// 批量导入数据
/// </summary>
/// <param name="dTable">需要导入的数据</param>
/// <param name="tableName">目标表名</param>
/// <returns></returns>
public bool SqlBulkCopyData(DataTable dTable, string tableName)
{
bool isSuc = false;
SqlBulkCopy bulkCopy = null;
if (!bInTrans)
{
this.OpenConn();
bulkCopy = new SqlBulkCopy(connection);
}
else
{
bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction);
}
bulkCopy.BatchSize = 500;
bulkCopy.BulkCopyTimeout = 5;
bulkCopy.DestinationTableName = tableName;
foreach (DataColumn column in dTable.Columns)
{
bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
}
try
{
bulkCopy.WriteToServer(dTable);
isSuc = true;
}
catch (Exception ex)
{
isSuc = false;
if (this.bInTrans)
{
this.RollbackTran();
}
throw ex;
}
finally
{
this.CloseConn();
}
return isSuc;
}

#endregion

#region ExecuteScalar Method

/// <summary>
/// 返回单个值
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="lstParams">参数集合</param>
/// <param name="comType">sql语句类型</param>
/// <returns></returns>
public object ExecuteScalar(string strSql, List<SqlParameter> lstParams = null, CommandType comType = CommandType.Text)
{
object rtnValue = null;
try
{
SqlCommand comm = PreSqlCommand(strSql, lstParams, comType);
rtnValue = comm.ExecuteScalar();
}
catch (Exception ex)
{
if (bInTrans)
{
this.RollbackTran();
}
throw ex;
}
finally
{
this.CloseConn();
}
return rtnValue;
}

#endregion

#region SqlDataReader Method

/// <summary>
/// 返回SqlDataReader
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="lstParams">参数集合</param>
/// <param name="comType">sql语句类型</param>
/// <returns></returns>
public SqlDataReader ExecuteDataReader(string strSql, List<SqlParameter> lstParams = null, CommandType comType = CommandType.Text)
{
SqlDataReader dataReader = null;
CommandBehavior behavior = CommandBehavior.Default;
if (!bInTrans)
{
behavior = CommandBehavior.CloseConnection;
}
try
{
SqlCommand comm = PreSqlCommand(strSql, lstParams, comType);
dataReader = comm.ExecuteReader(behavior);
}
catch (Exception ex)
{
if (bInTrans)
{
this.RollbackTran();
}
throw ex;
}
return dataReader;
}

#endregion

#region 返回DataTable
/// <summary>
/// 返回DataTable对象
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="parameters">参数数组</param>
/// <param name="comType">sql语句类型</param>
/// <returns>DataTable对象</returns>
public DataTable ExecuteDataTable(string sql, List<SqlParameter> parameters = null, CommandType comType = CommandType.Text)
{
DataTable rtnTable = new DataTable();
try
{
SqlCommand comm = this.PreSqlCommand(sql, parameters, comType);
SqlDataAdapter sda = new SqlDataAdapter(comm);
sda.Fill(rtnTable);
}
catch (Exception ex)
{
//如果在事务中回滚事务
if (this.bInTrans)
{
this.RollbackTran();
}
throw ex;
}
finally
{
this.CloseConn();
}
return rtnTable;
}

#endregion

#region 返回DataSet

/// <summary>
/// 返回DataSet对象
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="parameters">参数数组</param>
/// <param name="comType">sql语句类型</param>
/// <returns>DataSet对象</returns>
public DataSet ExecuteDataSet(string sql, List<SqlParameter> parameters = null, CommandType comType = CommandType.Text)
{
DataSet rtnSet = new DataSet();
try
{
SqlCommand comm = this.PreSqlCommand(sql, parameters, comType);
SqlDataAdapter sda = new SqlDataAdapter(comm);
sda.Fill(rtnSet);
return rtnSet;
}
catch (Exception ex)
{
//如果在事务中回滚事务
if (this.bInTrans)
{
this.RollbackTran();
}
throw ex;
}
finally
{
this.CloseConn();
}
}

#endregion

public void Dispose()
{
//
}
}
}

sqldbhelper的更多相关文章

  1. ASP.NET常用的SqlDbHelper类

    请引用 using System.Data;using System.Data.SqlClient; 两个命名空间. 可以满足常用的数据集,读取多条数据,以及增删改操作 代码: /// <sum ...

  2. SqlDBHelper常用方法

    /*============================================================= *.net连接数据库常用方法 *Author : dongny,Li * ...

  3. SqlDbHelper备份,做项目时方便应用(目前不太全,把自己项目中的逐渐转移过来)

    ****************************************** 这是官网新闻左侧类别那部分用到的 **************************************** ...

  4. C# 操作数据库常用的 SqlDbHelper

    原博客园转载于   https://www.cnblogs.com/felix-wang/p/6742785.html using System; using System.Collections.G ...

  5. 返回泛型集合的SqlDBHelper

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using Entity; ...

  6. 重拾MVC——第一天:数据库连接与SqlDbHelper

    这个 SqlDbHelper 是我参考网上的和以前用过的 SqlDbHelper 自己写的一个非常简单的东西,主要是记录自己的学习情况 首先在Web.config中配置数据库连接字符串: <co ...

  7. ASP.NET数据库连接类(SqlDBHelper)

    第一步:创建一个名为SqlDBHelper的类,用来作为联通数据库和系统之间的桥梁. 第二步:引入命名空间,如果System.Configuration.System.Transcations这两个命 ...

  8. .Net SqlDbHelper

    using System.Configuration; using System.Data.SqlClient; using System.Data; namespace ExamDAL { clas ...

  9. SQLSERVER单表CRUD通用方法

    一.适用场景 ①当你书写简单的增删改查心累了 ②当你的项目不考虑并发.高性能 ③当你追求更快速的开发效率 ④当你的业务只涉及单表 二.代码展示 ①单表Insert public bool Insert ...

随机推荐

  1. Intellij idea 乱码问题(英文操作系统)

    英文操作系统导致 Debug 下的变量查看时显示乱码,可通过改变字体解决此问题.

  2. iOS-Xcode上传后iTunes Connect构建版本不显示

    在升级到Xcode8版本以后大多数人会碰到这个问题-开开心心开发好一款app以后上传到iTunes后台提交审核,然而iTunes Connect后台活动栏里没有出现我们上传的app,确切的说是显示一会 ...

  3. 跟随标准与Webkit源码探究DOM -- 获取元素之getElementsByClassName

    按照类名获取元素 -- getElementsByClassName(HTML5) 标准 WHATWG 在Document与Element上均有定义,原型 HTMLCollection getElem ...

  4. 图文安装Windows Template Library - WTL Version 9.0

    从http://wtl.sourceforge.net/下载 WTL 9.0,或者点此链接下载:WTL90_4140_Final.zip,然后解压到你的VC目录下面, 我的地址是:C:\Program ...

  5. 十、EnterpriseFrameWork框架的分层架构及意义(控制器、业务对象、实体、Dao之间关系)

    本章内容主要包括两个方面,一.是框架分层(控制器.业务对象.实体.Dao)的详细说明,二.是对比常用三层结构的区别和优势: 本文要点: 1.框架中的各个分层详细说明 2.对比常用三层结构的区别和优势 ...

  6. win8磁盘占用100%的12种解决办法

    解决方法1:硬盘4K对齐,能减少磁盘占用100%情况.(大部分用户能解决) 解决方法2:检查硬盘AHCI驱动是否安装 解决方法3:通过 HD Tune Pro 5 专业的硬盘测试工具 检测硬盘健康度, ...

  7. [原]编译Android源码过程中遇到的问题

    编译Android源码的过程参考Android官网介绍: 1.下载Android源码的步骤:https://source.android.com/source/downloading.html 2.编 ...

  8. SQL截取字段字符串的方法

    set @str='WX15-53-H-53-99-15-335-23'; select @str as '字符串' select len(@str) as '字符长度' select charind ...

  9. Android使用SurfaceView实现墨迹天气的风车效果

    SurfaceView也是继承自View,它和我们以前接触到的View(Button.TextView等)最大的不同是,SurfaceView可以有一个单独的线程进行绘制,这个线程区别于UI线程(主线 ...

  10. SQL SERVER UNION和UNION ALL

    union与union allunion 缺省在合并结果集后消除重复项,union all 指定在合并结果集后保留重复项, 打个比喻吧 比如A表的数据是 A{ 1,4,5,9}       B{2,3 ...