• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

一个通用数据库访问类(C#,SqlClient)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 
return false;
}
else
{
return true; } } finally { delUserDBAccess.Close(); } }

 
 
DotNet常用类收集
本文转自: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(); } }


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
用VisualStudio2012+Xamarin搭建C#开发Andriod的环境发布时间:2022-07-13
下一篇:
C#调用存储过程简单完整例子发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap