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前台功能: ...
随机推荐
- Delphi经验总结(2)
Q: 怎么来改变ListBox的字体呢?就修改其中的一行. A: 先把ListBox1.Style 设成lbOwnerDrawFixed 然后在 OnDrawItem 事件下写下如下代码 proced ...
- Java for LeetCode 198 House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount ...
- [Android Pro] Android签名与认证详细分析之一(CERT.RSA剖析)
转载自:http://www.thinksaas.cn/group/topic/335450/ 一.Android签名概述 我们已经知道的是:Android对每一个Apk文件都会进行签名,在Apk文件 ...
- css3学习总结8--CSS3 3D转换
3D 转换 1. rotateX() 2. rotateY() otateX() 方法 通过 rotateX() 方法,元素围绕其 X 轴以给定的度数进行旋转. 示例: div { transform ...
- Java内部类的访问规则
1.内部类可以直接访问外部类中的成员,包括私有 原因:因为在内部类中持有一个外部类的应用,格式:外部类.this class Outer { private int x = 1; c ...
- javascript二叉树基本功能实现
都是常用的功能. 删除是最复杂的.. <!DOCTYPE html> <html lang="en"> <head> <meta char ...
- Java Hour 17 来个CURD吧(二)
有句名言,叫做10000小时成为某一个领域的专家.姑且不辩论这句话是否正确,让我们到达10000小时的时候再回头来看吧. 突然想到我最近一直在追的小说,作者每天都会更新两章,而且质量挺高.所以从这篇开 ...
- php 解决和避免form表单重复提交的方法
在提交表单的时候,可能遇到网速等导致页面突然加载变慢,用户重复地点击提交按钮,将在数据库产生多条数据,导致不可控情况. 比如下面的情况就会导致表单重复提交: 点击提交按钮两次. 点击刷新按钮. 使用浏 ...
- Oracle 连接 Visual Studio 的工具
Oracle 连接 Visual Studio 的工具 ① ② ③
- spark streaming中使用flume数据源
有两种方式,一种是sparkstreaming中的driver起监听,flume来推数据:另一种是sparkstreaming按照时间策略轮训的向flume拉数据. 最开始我以为只有第一种方法,但是尼 ...