C# - Dbhelp
dbhelp.cs
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 int ExecuteNonQuery(string sql) { DbCommand cmd = GetSqlStringCommond(sql); 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 DataSet ExecuteDataSet(string sql) { DbCommand cmd = GetSqlStringCommond(sql); DataSet ds = ExecuteDataSet(cmd); 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 DataTable ExecuteDataTable(string sql) { DbCommand cmd = GetSqlStringCommond(sql); DataTable dt = ExecuteDataTable(cmd); return dt; } 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(); } } }
基本的使用
private DbHelper db = new DbHelper(System.Configuration.ConfigurationManager.AppSettings["connstr"]); <appSettings> <add key="DbHelperProvider" value="System.Data.SqlClient"/> <add key="connstr" value="Data Source=(local);Initial Catalog=Demo;User ID=sa;Password=202063sb"/> </appSettings> 那么如何使用它呢?下面我给出一些基本的使用示例,基本能满足你大部分的数据库操作需要了. )直接执行sql语句 DbHelper db = new DbHelper(); DbCommand cmd = db.GetSqlStringCommond("insert t1 (id)values(‘haha‘)"); db.ExecuteNonQuery(cmd); 或者 db.ExecuteNonQuery("insert t1 (id)values(‘haha‘)"); )执行存储过程 DbHelper db = new DbHelper(); DbCommand cmd = db.GetStoredProcCommond("t1_insert"); db.AddInParameter(cmd, "@id", DbType.String, "heihei"); db.ExecuteNonQuery(cmd); )返回DataSet DbHelper db = new DbHelper(); DbCommand cmd = db.GetSqlStringCommond("select * from t1"); DataSet ds = db.ExecuteDataSet(cmd); 或者 db.ExecuteNonQuery(sql); )返回DataTable DbHelper db = new DbHelper(); DbCommand cmd = db.GetSqlStringCommond("t1_findall"); DataTable dt = db.ExecuteDataTable(cmd); 或者 DataTable dt = db.ExecuteDataTable(sql); )输入参数/输出参数/返回值的使用(比较重要哦) DbHelper db = new DbHelper(); DbCommand cmd = db.GetStoredProcCommond("t2_insert"); db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks); db.AddOutParameter(cmd, ); 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 )DataReader使用 DbHelper db = new DbHelper(); DbCommand cmd = db.GetStoredProcCommond("t2_insert"); db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks); db.AddOutParameter(cmd, ); 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 )事务的使用.(项目中需要将基本的数据库操作组合成一个完整的业务流时,代码级的事务是必不可少的哦) 以上我们好像没有指定数据库连接字符串,大家如果看下DbHelper的代码,就知道要使用它必须在config中配置两个参数,如下: 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, ); 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# - Dbhelp的更多相关文章
- 带事物处理的DBHelp和sql语句
DBHelp语句 using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...
- C# Access DBHelp
/* * By :落落 * URL: Www.MyLuoLuo.Com */ using System; using System.Collections.Generic; using System. ...
- DBHelp数据处理类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- 笔记8:winfrom连接数据库DBHelp
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...
- SQLite DBHelp
c#连接SQLite SQLite这个精巧的小数据库,无需安装软件,只需要一个System.Data.SQLite.DLL文件即可操作SQLite数据库.SQLite是一个开源数据库,现在已变得越来越 ...
- .Net下SQLite的DBHelp
怎样获取SqLite请参考初识SqlLite ---.net连接数据库,怎样在SQLite使用Linq请参考在C#中利用Nuget包使用SQLite数据库和Linq to SQLite using S ...
- C#winfrom最简DBHelp(数据库连接操作)
代码如下: //需引用命名空间 using System.Data; using System.Data.SqlClient; class DBHelper { //定义数据库连接语句,连接语句书写方 ...
- 平凡的KTV后台,不平凡的KTV数据
之前就是说过“一个项目有很多重要的步骤以及功能”,那我们现在就来看看对于KTV项目来说:后台是处于什么样的重要作用! 首先就得了解KTV后台的一些功能了: 1.歌曲管理 .歌手管理 .设置资源路径 2 ...
- 欢迎进入MyKTV前后台点歌系统展示
一个项目,一分收获:一个项目,一些资源.Ktv项目也是一样的,所以我想分享我的收获,让你们获得你需要的资源. 一. 那MyKTV点歌系统具体的功能有哪些呢?我们就来看看吧! 1.MyKTV前台功能: ...
随机推荐
- 2013 ACM/ICPC 长春网络赛E题
题意:给出一个字符串,要从头.尾和中间找出三个完全相等的子串,这些串覆盖的区间互相不能有重叠部分.头.尾的串即为整个字符串的前缀和后缀.问这个相同的子串的最大长度是多少. 分析:利用KMP算法中的ne ...
- Java入门的程序汇总
Java入门的基础程序,虽然很简单,也要多练习,下面有重点的总结一下 1.HelloWorld这个不说了 2.常量与变量部分 基本数据类型使用 public class Javashujuleixin ...
- ffplay mini 媒体播放器
下载 http://pan.baidu.com/s/1dDcp3lZ 一定要解压到 D:\ffplay\ 目录下 双击 OpenWith_FFPlay_mini.reg 注册ffplay 在视频文件名 ...
- jquery给height拼接动态变量
var sizeLength = "${list.size()}"; if(sizeLength==''){ sizeLength=0; } sizeLength=400*size ...
- jQuery工具函数
要点:1.字符串操作2.数组和对象操作3.测试操作4.URL 操作5.浏览器检测6.其他操作 工具函数是指直接依附于 jQuery 对象,针对 jQuery 对象本身定义的方法,即全局性的函数.它的作 ...
- 7.适配器模式(Adapter Pattern)
using System; namespace Test { /// <summary> /// 适配器模式主要解决的问题就是我们要调用的接口类型,无法满足我们新系统的使用需求, /// ...
- oracle 10g 学习之客户端安装和配置(2)
概述 Oracle 数据库是一种网络上的数据库, 它在网络上支持多用户, 支持服务器/客户机等部署(或配置) 服务器与客户机是软件概念, 它们与计算机硬件不存在一一对应的关系. 即: 同一台计算机既可 ...
- 修改stb_image.c以让Duilib直接支持Ico格式的图标显示
duilib不支持ico格式的图标资源, 但是我要想显示ico格式的图标... 发现网上那些转换ico为bmp或其它格式的都不是一个好办法, 也还是不能让duilib直接显示ico... 昨晚稍微研究 ...
- Android VLC播放器二次开发1——程序结构分析
最近因为一个新项目需要一个多媒体播放器,所以需要做个视频.音频.图片方面的播放器.也查阅了不少这方面的资料,如果要从头做一个播放器工作量太大了,而且难度也很大.所以最后选择了VLC作为基础,进行二次开 ...
- ubuntu apt-get 总结 install xxx -d能下载安装包(含依赖)不安装_和卸载(转载)
[举例] 目前常用的 ========== *更新本机中的数据库缓存: sudo apt-get update *查找包含部分关键字的软件包: sudo apt-cache search <你要 ...