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. 【linux】——FreeBSD 建立 SSH 连接慢的解决方法

    一般在编写 linux 程序的时候,会使用 SecureCRT 或者 xshell 等工具远程登录到 linux 服务器上.最近发现在建立 SSH 连接的时候,非常慢,但是建立连接成功之后可以正常使用 ...

  2. 15.6.8-sql小技巧

    取月头月尾: declare @someDay datetime,@firstDay datetime,@endDay datetime set @someDay='2015.2.2' ,) ,) s ...

  3. 点击弹出 +1放大效果 -- jQuery插件

    20140110更新: <!doctype html> <html> <head> <meta charset="UTF-8"> & ...

  4. ubuntu 修改默认root及密码

    安装完Ubuntu后忽然意识到没有设 置root密码,不知道密码自然就无法进入根用户下.到网上搜了一下,原来是这麽回事.Ubuntu的默认root密码是随机的,即每次开机都有一个新的 root密码.我 ...

  5. Android Studio配置和使用OpenCV3.x,不需要OpencvManager

    转载声明,本文转自CSDN:http://blog.csdn.net/qq_22033759/article/details/51156121 ps:本来在贴吧上有人问,想自己写的,但时间有限,当初自 ...

  6. [翻译]使用Swift在Xcode中创建自定义控件

    使用Swift在Xcode中创建自定义控件 原文 IBDesignable and IBInspectable With IBDesignable and IBInspectable, develop ...

  7. Windows下gvim的快捷键--“冒号+w+回车”真的很累人

    发现Windows下的gvim支持Ctrl+S保存,Ctrl+A全选,Ctrl+C复制,Ctrl+V粘贴,Ctrl+Z撤销 不过Ctrl+X貌似不太正常(可以剪切,但是不能粘贴) 可能要在安装目录下的 ...

  8. ubuntu 安装node.js + express + mongodb

    转载自http://my.oschina.net/reg/blog/289536 Ctrl + Alt + T,打开终端,输入以下命令安装: sudo apt-get install nodejs 安 ...

  9. c/c++:重载 覆盖 隐藏 overload override overwrite

    http://www.cnblogs.com/qlee/archive/2011/07/04/2097055.html 成员函数的重载.覆盖与隐藏成员函数的重载.覆盖(override)与隐藏很容易混 ...

  10. ADO.NET 3.5高级编程:应用LINQ&Entity Framework

    http://item.jd.com/10080604.html 第1部分 ADO.NET3.5概览第1章 使用ADO.NET3.5提供的新方法访问数据1.1 语言集成查询LINO1.1.1 LIQ  ...