博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[转载]DbHelper的常用数据库类
阅读量:5132 次
发布时间:2019-06-13

本文共 8492 字,大约阅读时间需要 28 分钟。

原文链接:
操作数据库是一个很麻烦的事情,下面是一个常用的依据工程原理的 DbHelper类
using System;using System.Data;using System.Data.Common;using System.Configuration;public class DbHelper{private static string dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"];private static string dbConnectionString = ConfigurationManager.AppSettings["DbHelperConnectionString"];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;}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){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;}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;}public DbDataReader ExecuteReader(DbCommand cmd){cmd.Connection.Open();DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);return reader;}public int ExecuteNonQuery(DbCommand cmd){cmd.Connection.Open();int ret = cmd.ExecuteNonQuery();cmd.Connection.Close();return ret;}public object ExecuteScalar(DbCommand cmd){cmd.Connection.Open();object ret = cmd.ExecuteScalar();cmd.Connection.Close();return ret;}    #endregion    #region 执行事务    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;}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;}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;}public int ExecuteNonQuery(DbCommand cmd, Trans t){cmd.Connection.Close();cmd.Connection = t.DbConnection;cmd.Transaction = t.DbTrans;int ret = cmd.ExecuteNonQuery();return ret;}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}public class Trans : 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(){dbTrans.Commit();this.Colse();}public void RollBack(){dbTrans.Rollback();this.Colse();}public void Dispose(){this.Colse();}public void Colse(){if (conn.State == System.Data.ConnectionState.Open){conn.Close();}}}那么如何使用它呢?下面我给出一些基本的使用示例,基本能满足你大部分的数据库操作需要了.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)返回DataSetDbHelper db = new DbHelper();DbCommand cmd = db.GetSqlStringCommond("select * from t1");DataSet ds = db.ExecuteDataSet(cmd);4)返回DataTableDbHelper 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 parameterint r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value6)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 parameterint r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value7)事务的使用.(项目中需要将基本的数据库操作组合成一个完整的业务流时,代码级的事务是必不可少的哦)public 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);elsedb.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);elsedb.ExecuteNonQuery(cmd, t);}以上我们好像没有指定数据库连接字符串,大家如果看下DbHelper的代码,就知道要使用它必须在config中配置两个参数,如下:

转载于:https://www.cnblogs.com/c3055/archive/2011/05/29/2062257.html

你可能感兴趣的文章
OpenCV之响应鼠标(三):响应鼠标信息
查看>>
Android 画图之 Matrix(一)
查看>>
List<T>列表通用过滤模块设计
查看>>
【模板】最小生成树
查看>>
设计模式之结构型模式
查看>>
poj2569
查看>>
使用pygal_maps_world.i18n中数据画各大洲地图
查看>>
sql server必知多种日期函数时间格式转换
查看>>
jQuery EasyUI 的下拉选择combobox后台动态赋值
查看>>
timeline时间轴进度“群英荟萃”
查看>>
python if else elif statement
查看>>
网络编程
查看>>
文本隐藏(图片代替文字)
查看>>
java面试题
查看>>
提高码力专题(未完待续)
查看>>
pair的例子
查看>>
前端框架性能对比
查看>>
uva 387 A Puzzling Problem (回溯)
查看>>
12.2日常
查看>>
同步代码时忽略maven项目 target目录
查看>>