本文转自:http://www.7139.com/jsxy/cxsj/c/200607/114291.html
使用ADO.NET时,每次数据库操作都要设置connection属性、建立connection、使用command、事务处理等,比较繁琐,有很多重复工作。能不能把这些繁琐的、常用的操作再封装一下,以更方便、安全地使用。下面这个类就是一种尝试:
using System;
using System.Data.SqlClient;
using System.Text;
using System.Data;
using System.Collections;
using System.Configuration;

public class DBAccess
{
///
/// Declare the ole db required objects
///

///
/// An ole db adapter to act as the bridge to the database
///
private SqlDataAdapter dbDataAdapter;
///
/// The connection to the database
///
private SqlConnection dbConnection;
///
/// The command for doing the inserts
///
private SqlCommand dbInsertCommand;
///
/// The command for doing the deletes
///
private SqlCommand dbDeleteCommand;
///

/// The command for doing the updates
///
private SqlCommand dbUpdateCommand;
///
/// The command for doing the Selects
///
private SqlCommand dbSelectCommand;
private SqlCommand dbSelectCommandofAdapter;
///
/// The command for get dataset
///
private SqlDataAdapter dataAdapterCommand;
///
/// The data reader for the application
///
public SqlDataReader dbDataReader;

///
/// Declare an enum to allow internal tracking of commands 
///
enum COMMAND{ NONE, INSERT, UPDATE, DELETE, SELECT,DATASET };

///
/// Internal member for tracking command progress
///
private COMMAND command;
///
/// String to hold error messages if a command fails
///
private string error;
///
/// Get a stored error message if ExecuteCommand fails
///
public string ErrorMessage
{
get
{
return error;
}
}
///
/// bool holder for is open
///
private bool bOpen;
///
/// Check to see if a data base is open
///
public bool IsOpen
{
get
{
return bOpen;
}
}

///
/// Declare a string object for the insert command
///
public string InsertCommand 
{
get
{
return dbInsertCommand.CommandText;
}
set 
{
command = COMMAND.INSERT;
dbInsertCommand.CommandText = value;
}
}
///
/// Declare a string object for the delete command
///
public string DeleteCommand
{
get
{
return dbDeleteCommand.CommandText;
}
set
{
command = COMMAND.DELETE;
dbDeleteCommand.CommandText = value;
}
}
///
/// Declare a string object for the update command
计算机教程一个通用数据库访问类(C#,SqlClient)来自www.itwen.comIT WEN计算机教程网

///
public string UpdateCommand
{
get
{
return dbUpdateCommand.CommandText;
}
set
{
command = COMMAND.UPDATE;
dbUpdateCommand.CommandText = value;
}
}
///
/// Declare a string object for the select command
///
public string SelectCommand
{
get
{
return dbSelectCommand.CommandText;
}
set
{
command = COMMAND.SELECT;
dbSelectCommand.CommandText = value;
}
}
public string SelectDataSetCommand
{
get
{
return dataAdapterCommand.SelectCommand.CommandText;
}
set
{
command = COMMAND.DATASET;
dataAdapterCommand.SelectCommand.CommandText = value;
}
}
///
/// Get the reader from the class
///
public SqlDataReader GetReader
{
get
{
switch( command )
{
case COMMAND.NONE: return null; 
case COMMAND.DELETE: return DeleteReader; 
case COMMAND.INSERT: return InsertReader; 
case COMMAND.SELECT: return SelectReader; 
case COMMAND.UPDATE: return UpdateReader; 
default: return null; 
}
}
}
public DataSet GetDataSet
{
get
{
switch( command )
{
case COMMAND.DATASET: return SelectDataSet(); 
default: return null; 
}
}
}
public DataSet SelectDataSet()
{
try
{
dataAdapterCommand.SelectCommand.Connection = dbConnection;
DataSet dataset = new DataSet();
dataAdapterCommand.Fill(dataset);
return dataset;
}
catch (Exception exp)
{
error = exp.Message;
return null;
}
}
///
/// Execute the command that has been set up previously
///
/// A boolean value indicating true or false
public bool ExecuteCommand()
{
bool bReturn = false;
if( command == COMMAND.NONE )
{
return bReturn;
}
else if( command == COMMAND.SELECT )
{
/// select only returns true as the get reader function will

/// execute the command
try
{
if( dbDataReader != null )
{
dbDataReader.Close();
dbDataReader = null;
}
bReturn = true;
/// return bReturn;
}
catch( SqlException exp )
{
error = "dbException thrown when trying to Select, error given = " + exp.Message + " check the sql";
return bReturn = false;
}
}
else if( command == COMMAND.DATASET )
{
return bReturn; 
}
else 
{
int nAffected = -1;
if( dbDataReader != null )
{
dbDataReader.Close();
dbDataReader = null;
}
/// get the transaction object from the connection
SqlTransaction trans = dbConnection.BeginTransaction();
try
{
/// create a nested transaction on the connection transaction
switch( command )
{
case COMMAND.DELETE: dbDeleteCommand.Transaction = trans; break;
case COMMAND.INSERT: dbInsertCommand.Transaction = trans; break;
case COMMAND.UPDATE: dbUpdateCommand.Transaction = trans; break;
}

/// execute the command
switch( command )
{
case COMMAND.DELETE: nAffected = dbDeleteCommand.ExecuteNonQuery(); break;
case COMMAND.INSERT: nAffected = dbInsertCommand.ExecuteNonQuery(); break;
case COMMAND.UPDATE: nAffected = dbUpdateCommand.ExecuteNonQuery(); break;
}
}
catch( InvalidOperationException ioexp )
{
StringBuilder buildError = new StringBuilder();
buildError.Append( "InvalidOperationException thrown when trying to " );
switch( command )
{
case COMMAND.DELETE: buildError.Append( "Delete" ); break;
case COMMAND.INSERT: buildError.Append( "Insert" ); break;
case COMMAND.UPDATE: buildError.Append( "Update" ); break;
}
buildError.Append( ", error given = " + ioexp.Message + " check the sql" );
error = buildError.ToString();
return bReturn = false;
}
catch( SqlException dbexp )
{
StringBuilder buildError = new StringBuilder();
buildError.Append( "InvalidOperationException thrown when trying to " );

switch( command )
{
case COMMAND.DELETE: buildError.Append( "Delete" ); break;
case COMMAND.INSERT: buildError.Append( "Insert" ); break;
case COMMAND.UPDATE: buildError.Append( "Update" ); break;
}
buildError.Append( ", error given = " + dbexp.Message + " check the sql" );
error = buildError.ToString();
return bReturn = false;
}
finally
{
/// commit the command
if( nAffected == 1 )
{
switch( command )
{
case COMMAND.DELETE: dbDeleteCommand.Transaction.Commit(); break;
case COMMAND.INSERT: dbInsertCommand.Transaction.Commit(); break;
case COMMAND.UPDATE: dbUpdateCommand.Transaction.Commit(); break;
}
//trans.Commit();
bReturn = true;
}
else /// if something went wrong rollback
{
switch( command )
{
case COMMAND.DELETE: dbDeleteCommand.Transaction.Rollback(); break;
case COMMAND.INSERT: dbInsertCommand.Transaction.Rollback(); break;
case COMMAND.UPDATE: dbUpdateCommand.Transaction.Rollback(); break;
}

//trans.Rollback();
bReturn = false;
}
}
}
return bReturn;
}

#region select functions
///
/// Get the Select reader from the select command
///
private SqlDataReader SelectReader
{
get
{
if( dbDataReader != null )
{
if( dbDataReader.IsClosed == false )
{
dbDataReader.Close();
dbDataReader = null;
}
}
dbDataReader = dbSelectCommand.ExecuteReader();
return dbDataReader;
}
}
///
/// Get the Update reader from the update command
///
private SqlDataReader UpdateReader
{
get 
{
if( dbDataReader.IsClosed == false )
dbDataReader.Close();
dbDataReader = dbSelectCommand.ExecuteReader();
return dbDataReader;
}
}
///
/// Get the Insert Reader from the Insert Command
///

private SqlDataReader InsertReader
{
get
{
if( dbDataReader.IsClosed == false )
dbDataReader.Close();
dbDataReader = dbSelectCommand.ExecuteReader();
return dbDataReader;
}
}
///
/// Get the Delete Reader from the Delete Command
///
private SqlDataReader DeleteReader
{
get
{
if( dbDataReader != null )
{
if( dbDataReader.IsClosed == false )
{
dbDataReader.Close();
dbDataReader = null;
}
}
dbDataReader = dbSelectCommand.ExecuteReader();
return dbDataReader;
}
}
#endregion

///
/// Standard Constructor
///
public DBAccess()
{
/// NOTE That we are not setting the commands up the way the wizard would
/// but building them more generically
// create the command variables
dbDataAdapter = new SqlDataAdapter();
dbConnection = new SqlConnection();
dbSelectCommand = new SqlCommand();
dbDeleteCommand = new SqlCommand();
dbUpdateCommand = new SqlCommand();
dbInsertCommand = new SqlCommand();

/// set up the adapter 
dbDataAdapter.DeleteCommand = dbDeleteCommand;
dbDataAdapter.InsertCommand = dbInsertCommand;
dbDataAdapter.SelectCommand = dbSelectCommand;
dbDataAdapter.UpdateCommand = dbUpdateCommand;
/// make sure everyone knows what conection to use
dbSelectCommand.Connection = dbConnection;
dbDeleteCommand.Connection = dbConnection;
dbUpdateCommand.Connection = dbConnection;
dbInsertCommand.Connection = dbConnection;
command = COMMAND.NONE;
dbDataReader = null;
dbSelectCommandofAdapter = new SqlCommand();
dataAdapterCommand = new SqlDataAdapter();
dataAdapterCommand.SelectCommand = dbSelectCommandofAdapter;
}
public void Open()
{
/// set up the connection string
StringBuilder strBuild = new StringBuilder();
//Connection的属性从配置文件读取
strBuild.AppendFormat(ConfigurationSettings.AppSettings["DBConnection"]);

dbConnection.ConnectionString = strBuild.ToString();
try
{
dbConnection.Open();
bOpen = true;
}
catch (Exception exp)
{
error = exp.Message;
}

}

///
/// Close the currently open connection
///
public void Close()
{
if (dbDataReader != null)
{
if( dbDataReader.IsClosed == false )
{
dbDataReader.Close();
dbDataReader = null;
}
}
dbConnection.Close();
}
}
使用示例:
Insert操作,新建用户:
public bool NewUser()
{
DBAccess newUserDBAccess = new DBAccess();
StringBuilder sqlStr = new StringBuilder();
sqlStr.Append( "Insert into userTable(usrName,pwd,name,depart,role,available) values(");
sqlStr.Append( "'" + usrName + "',");
sqlStr.Append( "'" + pwd + "',");
sqlStr.Append( "'" + name + "',");
sqlStr.Append( "'" + depart + "',");
sqlStr.Append( "'" + role + "',");
sqlStr.Append(1);
sqlStr.Append( ")");

newUserDBAccess.InsertCommand = sqlStr.ToString();
newUserDBAccess.Open();
try
{
if (!newUserDBAccess.ExecuteCommand()) 
{
errMsg = newUserDBAccess.ErrorMessage;

return false;
}
else
{
return true;
}
}
finally
{
newUserDBAccess.Close();
}
}
Update操作,修改用户信息:
public bool ModifyUser()
{
DBAccess modifyUserDBAccess = new DBAccess();
StringBuilder sqlStr = new StringBuilder();
sqlStr.Append( "update userTable set ");
sqlStr.Append( " usrName = ");
sqlStr.Append( "'" + usrName + "',");
sqlStr.Append( " name =");
sqlStr.Append( "'" + name + "',");
sqlStr.Append( " pwd =");
sqlStr.Append( "'" + pwd + "',");
sqlStr.Append( " depart =");
sqlStr.Append( "'" + depart + "',");
sqlStr.Append( " role =");
sqlStr.Append( "'" + role + "'");
sqlStr.Append( " where usrID = ");
sqlStr.Append(id);

modifyUserDBAccess.UpdateCommand = sqlStr.ToString();
modifyUserDBAccess.Open();
try
{
if (!modifyUserDBAccess.ExecuteCommand()) 
{
errMsg = modifyUserDBAccess.ErrorMessage;

return false;
}
else
{
return true;
}
}
finally
{
modifyUserDBAccess.Close();
}
}
Delete操作,删除用户:
public static bool DelUser(int usrID)
{
DBAccess delUserDBAccess = new DBAccess();
StringBuilder sqlStr = new StringBuilder();
sqlStr.Append( "update userTable set ");
sqlStr.Append( " available =");
sqlStr.Append(0);
sqlStr.Append( " where usrID = ");
sqlStr.Append(usrID);

delUserDBAccess.UpdateCommand = sqlStr.ToString();
delUserDBAccess.Open();
try
{
if (!delUserDBAccess.ExecuteCommand()) 

return false;
}
else
{
return true; } } finally { delUserDBAccess.Close(); } }

 
 

一个通用数据库访问类(C#,SqlClient)的更多相关文章

  1. DataAccess通用数据库访问类,简单易用,功能强悍

    以下是我编写的DataAccess通用数据库访问类,简单易用,支持:内联式创建多个参数.支持多事务提交.支持参数复用.支持更换数据库类型,希望能帮到大家,若需支持查出来后转换成实体,可以自行扩展dat ...

  2. 学习实践:使用模式,原则实现一个C++数据库访问类

    一.概述 在我参与的多个项目中,大家使用libMySQL操作MySQL数据库,而且是源码即复用,在多个项目中有多套相同或相似的源码,这样的复用方式给开发带来了不变,而且libMySQL的使用比较麻烦, ...

  3. ADO.NET通用数据库访问类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  4. C# 通用数据访问类(SqlHelper)

    [转]C# 通用数据访问类(SqlHelper) 注:本文转自http://www.tzwhx.com/newOperate/html/3/31/312/13080.htmlVisual C# 动态操 ...

  5. [转]DbHelper通用数据库访问帮助类

    之前我一直都是在博客园中查看各位高手的博文,确实学到了不少知识,不过比较少写博客,现在就把我自己在项目实施过程中使用到比较好的技术框架写出来,希望能让更多的人了解和学习. 通常我们在开发使用数据库访问 ...

  6. 我也来写:数据库访问类DBHelper

    一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...

  7. 我也来写:数据库访问类DBHelper(转)

    一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...

  8. C#.NET数据库访问类DBHelper

    这是一个与C# .NET通用的数据库访问类,包含了工厂模式.事务处理等安全机制. 调用方式: DBHelper db = new DBHelper(); DbCommand cmd = db.GetS ...

  9. 通用数据库操作类,前端easyui-datagrid,form

    实现功能:     左端datagrid显示简略信息,右侧显示选中行详细信息,数据库增删改 (1)点击选中行,右侧显示详细信息,其中[新增].[修改].[删除]按钮可用,[保存]按钮禁用 (2)点击[ ...

随机推荐

  1. 218. The Skyline Problem

    题目: A city's skyline is the outer contour of the silhouette formed by all the buildings in that city ...

  2. linux系统的crond服务

    linux系统中有一个服务,用来做周期性运行的例行任务,这个服务就是crond服务.执行这项服务的命令 就是crontab命令了.而linux下的任务调度又分为系统任务调度和用户任务调度两个大类. 系 ...

  3. P137、面试题23:从上往下打印二叉树

    题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印.例如输入如图的二叉树,则依次打印出8,6,10,5,7,9,11.(其实是按层遍历)二叉树结点的定义如下:struct Bin ...

  4. Windows 各种计时函数总结

    本文对Windows平台下常用的计时函数进行总结,包括精度为秒.毫秒.微秒三种精度的 5种方法.分为在标准C/C++下的二种time()及clock(),标准C/C++所以使用的time()及cloc ...

  5. bash 正则表达式匹配,一行文本中 “包含 ABC” 并且 “不包含 XYZ”

    bash 正则表达式匹配,一行文本中  “包含 ABC”  并且  “不包含 XYZ” A文件: XXXX ABC XXX4444444444444444XXXX ABC XXX XYZ6666666 ...

  6. insert /*+APPEND*/ 各种insert 插入速度比较

    SQL> select count(*) from t;COUNT(*)----------5442048****************************SQL> alter ta ...

  7. SQL RIGHT JOIN 关键字

    SQL RIGHT JOIN 关键字 RIGHT JOIN 关键字会右表 (table_name2) 那里返回所有的行,即使在左表 (table_name1) 中没有匹配的行. RIGHT JOIN ...

  8. 【转】android开发工具Eclipse,androidStudio,adt网盘下载--不错

    原文网址:http://tools.android-studio.org/index.php/85-tools/109-android-tools-download

  9. WCF 学习总结3 -- 实例模式

    通过WCF的ServiceBehaviorAttribute设定InstanceContextMode有下面的3中模式: 1. Single —— 表示所有的客户端共享一个会话(服务对象)(服务关闭时 ...

  10. java 垃圾回收(堆内存)、以及栈内存的释放

    一.Java的垃圾回收机制———解疑 Java的垃圾回收机制是Java虚拟机提供的能力,用于在空闲时间以不定时的方式动态回收无任何引用的对象占据的内存空间. 需要注意的是:垃圾回收回收的是无任何引用的 ...