其中的部分内容是别人的,我修改过了并加入了详细的注释!!!

一、这个DBHelper的大致块儿如下图:

二、下面是具体的源代码:

//命名空间。。。。。

using System;
using System.Data;
using System.Data.Common;
using System.Configuration;

namespace Common
{
   public class DBHelper
  {

//属性区。。。。。
     private static string dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"];
     private static string dbConnectionString = ConfigurationManager.AppSettings["Connstr"];//我的数据库连接字符串,其名称是:Connstr
     private DbConnection connection;

//不带参数构造器。(暴露出去方便调用)
public DBHelper()
{
this.connection = CreateConnection(DBHelper.dbConnectionString);//创建连接
}
//带参数构造器。(暴露出去方便调用)
public DBHelper(string connectionString)
{
this.connection = CreateConnection(connectionString);//创建连接
}
/****************************************************< 直接连接 >***********************************************************/
public static DbConnection CreateConnection()

{
DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DBHelper.dbProviderName);
DbConnection dbconn = dbfactory.CreateConnection();
dbconn.ConnectionString = DBHelper.dbConnectionString;
return dbconn;
}

/****************************************************< 带连接字符串的连接 >************************************/
public static DbConnection CreateConnection(string connectionString)

{
     DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DBHelper.dbProviderName);
     DbConnection dbconn = dbfactory.CreateConnection();
     dbconn.ConnectionString = connectionString;
     return dbconn;
}

/****************************************************< 获取储存过程 >******************************************/
public DbCommand GetStoredProcCommond(string storedProcedure)

{
     DbCommand dbCommand = connection.CreateCommand();
     dbCommand.CommandText = storedProcedure;
     dbCommand.CommandType = CommandType.StoredProcedure;
     return dbCommand;
}

/****************************************************< 获取SQL语句命令 >**************************************/
public DbCommand GetSqlStringCommond(string sqlQuery)

{
    DbCommand dbCommand = connection.CreateCommand();
    dbCommand.CommandText = sqlQuery;
    dbCommand.CommandType = CommandType.Text;
    return dbCommand;
}

#region =======================================《 增加参数集合 》=============================
public void AddParameterCollection(DbCommand cmd, DbParameterCollection dbParameterCollection)
{
    foreach (DbParameter dbParameter in dbParameterCollection)//foreach(数据类型 标识符 in 表达式)
   {
       cmd.Parameters.Add(dbParameter);//增加参数
    }
}

/****************************************************< 增加输出参数 >*******************************************/
public void AddOutParameter(DbCommand cmd, string parameterName, DbType dbType, int size)

{
      DbParameter dbParameter = cmd.CreateParameter();
      dbParameter.DbType = dbType;
      dbParameter.ParameterName = parameterName;
      dbParameter.Size = size;
      dbParameter.Direction = ParameterDirection.Output;
      cmd.Parameters.Add(dbParameter);
}

/****************************************************< 增加输入参数 >********************************************/
public void AddInParameter(DbCommand cmd, string parameterName, DbType dbType, object value)

{
      DbParameter dbParameter = cmd.CreateParameter();
      dbParameter.DbType = dbType;
      dbParameter.ParameterName = parameterName;
      dbParameter.Value = value;
      dbParameter.Direction = ParameterDirection.Input;
      cmd.Parameters.Add(dbParameter);
}

/****************************************************< 增加返回输入参数 >****************************************/
public void AddReturnParameter(DbCommand cmd, string parameterName, DbType dbType)

{
    DbParameter dbParameter = cmd.CreateParameter();
    dbParameter.DbType = dbType;
    dbParameter.ParameterName = parameterName;
    dbParameter.Direction = ParameterDirection.ReturnValue;
    cmd.Parameters.Add(dbParameter);
}

/****************************************************< 获取参数 >*********************************************/
public DbParameter GetParameter(DbCommand cmd, string parameterName)
{
    return cmd.Parameters[parameterName];
}
#endregion

#region========================================《 普通执行 》============================
public DataSet ExecuteDataSet(DbCommand cmd)
{
    DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DBHelper.dbProviderName);
    DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
    dbDataAdapter.SelectCommand = cmd;
    DataSet ds = new DataSet();
   dbDataAdapter.Fill(ds);
   return ds;
}

/****************************************************< 执行DataTable >******************************************/
public DataTable ExecuteDataTable(DbCommand cmd)
{
    DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DBHelper.dbProviderName);
    DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
    dbDataAdapter.SelectCommand = cmd;
    DataTable dataTable = new DataTable();
    dbDataAdapter.Fill(dataTable);
    return dataTable;
}

/****************************************************< 执行Reader >********************************************/
public DbDataReader ExecuteReader(DbCommand cmd)
{
    cmd.Connection.Open();
    DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    return reader;
}

/****************************************************< 执行SQL语句,并返回受到这条语句而改变的列 >*******************/
public int ExecuteNonQuery(DbCommand cmd)
{
    cmd.Connection.Open();
    int ret = cmd.ExecuteNonQuery();
    cmd.Connection.Close();
    return ret;
}

/*******************************< 执行SQL语句,从数据库中检索单个值返回值是object类型 >**************************/
public object ExecuteScalar(DbCommand cmd)
{
   cmd.Connection.Open();
   object ret = cmd.ExecuteScalar();
   cmd.Connection.Close();
   return ret;
}
#endregion

#region=====================================《 带事务的执行 》===============================
/****************************************************< 执行DataSet事务 >******************************************/
public DataSet ExecuteDataSet(DbCommand cmd,Trans t)
{
    cmd.Connection = t.DbConnection;
    cmd.Transaction = t.DbTrans;
    DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DBHelper.dbProviderName);
    DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
    dbDataAdapter.SelectCommand = cmd;
    DataSet ds = new DataSet();
    dbDataAdapter.Fill(ds);
    return ds;
}

/****************************************************< 执行DataTable事务 >*****************************************/
public DataTable ExecuteDataTable(DbCommand cmd, Trans t)
{
    cmd.Connection = t.DbConnection;
    cmd.Transaction = t.DbTrans;
    DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DBHelper.dbProviderName);
    DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
    dbDataAdapter.SelectCommand = cmd;
    DataTable dataTable = new DataTable();
    dbDataAdapter.Fill(dataTable);
    return dataTable;
}

/****************************************************< 执行Reader事务 >********************************************/
public DbDataReader ExecuteReader(DbCommand cmd, Trans t)
{
      cmd.Connection.Close();
      cmd.Connection = t.DbConnection;
      cmd.Transaction = t.DbTrans;
      DbDataReader reader = cmd.ExecuteReader();
      DataTable dt = new DataTable();
      return reader;
}

/****************************************************< ExecuteNonQuery >******************************************/
public int ExecuteNonQuery(DbCommand cmd, Trans t)
{
     cmd.Connection.Close();
     cmd.Connection = t.DbConnection;
     cmd.Transaction = t.DbTrans;
     int ret = cmd.ExecuteNonQuery();
     return ret;
}

/****************************************************< ExecuteScalar >*********************************************/
public object ExecuteScalar(DbCommand cmd, Trans t)
{
    cmd.Connection.Close();
    cmd.Connection = t.DbConnection;
    cmd.Transaction = t.DbTrans;
    object ret = cmd.ExecuteScalar();
    return ret;
}
#endregion
}

#region=================================================《 事务 》================================
public class Trans : IDisposable //IDisposable 接口:定义一种释放分配的非托管资源的方法
{
   private DbConnection conn;//连接
   private DbTransaction dbTrans;//事务

public DbConnection DbConnection
{
    get { return this.conn; }
}

public DbTransaction DbTrans
{
    get { return this.dbTrans; }
}

public Trans()
{
   conn = DBHelper.CreateConnection();
   conn.Open();
   dbTrans = conn.BeginTransaction();
}

public Trans(string connectionString)
{
   conn = DBHelper.CreateConnection(connectionString);
   conn.Open();
   dbTrans = conn.BeginTransaction();
}

public void Commit()//commit操作
{
    dbTrans.Commit();
    this.Colse();
}

public void RollBack()//RollBack操作
{
    dbTrans.Rollback();
    this.Colse();
}

public void Dispose()
{
    this.Colse();
}

public void Colse()
{
    if (conn.State == System.Data.ConnectionState.Open)
{
    conn.Close();
}
}
}
#endregion
}

三、数据库连接字符串

四、使用DBHelper的Demo

    

1、直接执行sql语句

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("insert t1 (id)values('haha')");
        db.ExecuteNonQuery(cmd);

2、执行存储过程

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t1_insert");
        db.AddInParameter(cmd, "@id", DbType.String, "heihei");
        db.ExecuteNonQuery(cmd);

3、返回DataSet

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("select * from t1");
        DataSet ds = db.ExecuteDataSet(cmd);

4、返回DataTable

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("t1_findall");
        DataTable dt = db.ExecuteDataTable(cmd);

5、输入参数/输出参数/返回值的使用(比较重要哦)

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
        db.AddOutParameter(cmd, "@outString", DbType.String, 20);
        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);

        db.ExecuteNonQuery(cmd);

       string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
      int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value

6)DataReader使用

      DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
        db.AddOutParameter(cmd, "@outString", DbType.String, 20);
        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);

 using (DbDataReader reader = db.ExecuteReader(cmd))
 {//该处克添加您需要的代码。。。
            dt.Load(reader);
        }
 string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
 int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value

7、事务的使用.(项目中需要将基本的数据库操作组合成一个完整的业务流时,代码级的事务是必不可少的哦)

    pubic void DoBusiness()
 {
 using (Trans t = new Trans())
 {
 try
 {
                D1(t);
 throw new Exception();//如果有异常,会回滚滴
                D2(t);
                t.Commit();
            }
 catch
 {
                t.RollBack();
            }
        }
    }
 public void D1(Trans t)
 {
        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
        db.AddOutParameter(cmd, "@outString", DbType.String, 20);
        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);

 if (t == null) db.ExecuteNonQuery(cmd);
 else db.ExecuteNonQuery(cmd,t);
string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
 int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value
    }
 public void D2(Trans t)
 {
        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("insert t1 (id)values('..')");        
 if (t == null) db.ExecuteNonQuery(cmd);
 else db.ExecuteNonQuery(cmd, t);
    }

五、我不造程序,我只是程序搬运工!!!

我的C# - Web - DAL- DBHelper.cs的更多相关文章

  1. System.Web.Mvc.HttpGetAttribute.cs

    ylbtech-System.Web.Mvc.HttpGetAttribute.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, P ...

  2. System.Web.Mvc.RouteAttribute.cs

    ylbtech-System.Web.Mvc.RouteAttribute.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, Pub ...

  3. System.Web.Mvc.HttpPostAttribute.cs

    ylbtech-System.Web.Mvc.HttpPostAttribute.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, ...

  4. System.Web.Mvc.RoutePrefixAttribute.cs

    ylbtech-System.Web.Mvc.RoutePrefixAttribute.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutra ...

  5. System.Web.Mvc.JavaScriptResult.cs

    ylbtech-System.Web.Mvc.JavaScriptResult.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, P ...

  6. System.Web.Mvc.ActionResult.cs

    ylbtech-System.Web.Mvc.ActionResult.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, Publi ...

  7. System.Web.Mvc.IAuthorizationFilter.cs

    ylbtech-System.Web.Mvc.IAuthorizationFilter.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutra ...

  8. System.Web.Mvc.IActionFilter.cs

    ylbtech-System.Web.Mvc.IActionFilter.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, Publ ...

  9. System.Web.Mvc.Controller.cs

    ylbtech-System.Web.Mvc.Controller.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicK ...

  10. System.Web.Mvc.ControllerBase.cs

    ylbtech-System.Web.Mvc.ControllerBase.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, Pub ...

随机推荐

  1. 如何使用 Laravel Facades ?

    Facade 布局是在面向对象编程中经常使用的一种软件设计布局方式.Facade 实际上是一种包括复杂函数库的类,提供了更加简洁易读的接口.Facade 布局还能为一组结构复杂.设计简陋的 API 提 ...

  2. Connect them

    zoj3204: 最小生成树,要求最小字典序的解. 用kruscal算法,先排序,输出的时候也要排序. /* zoj3204 解题思路: 赤裸裸的最小生成树.只是要求输出字典序最小的连接方案. 所以在 ...

  3. sequence使用

    SQL> create sequence seq1 minvalue 1 maxvalue 999999999999999999999999999 start with 0 increment ...

  4. simulink下直接代码生成

    连接好DSP,打开Matlab,首先必须要更改环境,要不不能编译通过 输入C2000lib,打开库, 在C2833X DSP Chip Support中添加外设,然后在C2000 Target Pre ...

  5. 【PNG格式中文详解】

        技术文档(Document)   PNG格式 PNG是20世纪90年代中期开始开发的图像文件存储格式,其目的是企图替代GIF和TIFF文件格式,同时增加一些GIF文件格式所不具备的特性.流式网 ...

  6. java对Ldap操作2

    package ldap.pojo;import java.util.List;/** * @author 张亮  * ldap用户属性信息数据类 */public class LdapPersonI ...

  7. Self-numbers 2 - SGU 108

    翻译:引自 http://www.cnblogs.com/yylogo/archive/2011/06/09/SGU-108.html 在1949年印度的数学假D.R. Kaprekar发现了一种叫做 ...

  8. C基础

    一.关于整型数据 1.整型常量:十进制数前面可以加+.-号,但是不能有前缀0 八进制数:必须以前缀0开头,不是O.不能加负号(-),否则不能识别. 十六进制数:前缀必须为0x或者0X.不能加负号(-) ...

  9. Partition算法剖析

    博文链接:http://haoyuanliu.github.io/2016/12/18/Partition%E7%AE%97%E6%B3%95%E5%89%96%E6%9E%90/ 对,我是来骗访问量 ...

  10. C# 保存窗口为图片(保存纵断面图)

    源代码例如以下: #region 保存纵断面截图 private void button_save_Click(object sender , EventArgs e) { SaveFileDialo ...