ADONET的一个帮助类库只须一个连接一条SQL语句轻松实现数据库的查旬再加一个object 轻松实现数据库的增删改
该类库根据是否需要事务可分为两个部分分别由三个构造方法决定
命名空间DBAssistant类DBAssist
方法ExecNoQueryWithTran() 实现带事务的增删改返回(int)影响的行数
方法 ExecNoQuery()实现不带事务的增删改返回(int) 影响的行数
方法ExecScalar() 实现返回首行首列的查询返回(object)
方法ExecSelect() 返回SqlDataReader
方法GetDataSet() 返回DataSet
using System;
using SystemCollectionsGeneric;
using SystemText;
using SystemData;
using SystemDataSqlClient;
using WriteException;
namespace DBAssistant
{
public class DBAssist
{
/// <summary>
/// 重载的构造方法
/// </summary>
public DBAssist() { }
public DBAssist(string strSqlSqlConnection conn)
{
thisStrSql = strSql;
thisConn = conn;
}
public DBAssist(string strSqlobject objSqlConnection conn)
{
thisStrSql = strSql;
thisObj = obj;
thisConn = conn;
}
public DBAssist(string strSql object obj SqlConnection connSqlTransaction sqlTran)
{
thisStrSql = strSql;
thisObj = obj;
thisConn = conn;
thissqlTran = sqlTran;
}
/// <summary>
/// sql语句
/// </summary>
string strSql;
public string StrSql
{
get { return strSql; }
set { strSql = value; }
}
/// <summary>
/// 要操作的对象需要对数据库操作的数据存于其中
/// </summary>
object obj;
public object Obj
{
get { return obj; }
set { obj = value; }
}
/// <summary>
/// 连接
/// </summary>
SqlConnection conn;
public SqlConnection Conn
{
get { return conn; }
set { conn = value; }
}
/// <summary>
/// 事务
/// </summary>
SqlTransaction sqlTran;
public SqlTransaction SqlTran
{
get { return sqlTran; }
set { sqlTran = value; }
}
public object count;
/// <summary>
/// 带事务增删改方法
/// </summary>
/// <returns>int</returns>
public int ExecNoQueryWithTran()
{
int num = ;
try
{
using (SqlCommand cmd = new SqlCommand(strSql conn))
{
cmdTransaction = sqlTran;
num = cmdExecuteNonQuery();
//SqlTranCommit();
}
}
catch (Exception ex)
{
WriExceptionWrite(ex);
//SqlTranRollback();
}
return num;
}
/// <summary>
/// 不带事务的增删改方法
/// </summary>
/// <returns>int</returns>
public int ExecNoQuery()
{
int num = ;
try
{
using (SqlCommand cmd = new SqlCommand(strSql conn))
{
num = cmdExecuteNonQuery();
}
}
catch (Exception ex)
{
WriExceptionWrite(ex);
}
return num;
}
/// <summary>
/// 返回 SqlDataReader 的查询方法
/// </summary>
/// <returns>SqlDataReader</returns>
public SqlDataReader ExecSelect()
{
SqlDataReader dr = null;
try
{
SqlCommand cmd = new SqlCommand(strSql conn);
dr = cmdExecuteReader(CommandBehaviorCloseConnection);
return dr;
}
catch (Exception ex)
{
WriExceptionWrite(ex);
}
return null;
}
/// <summary>
/// 调用ExecuteScalar()方法返回 object 的查询方法
/// </summary>
/// <returns>Object</returns>
public object ExecScalar()
{
count=null;
try
{
using (SqlCommand cmd = new SqlCommand(strSql conn))
{
count = cmdExecuteScalar();
}
}
catch (Exception ex)
{
WriExceptionWrite(ex);
}
return count;
}
DataSet ds;
/// <summary>
/// 返回DataSet的查询方法
/// </summary>
/// <returns>DataSet</returns>
public DataSet GetDataSet()
{
ds = null;
using (SqlDataAdapter sda = new SqlDataAdapter(strSql conn))
{
using (ds = new DataSet())
{
sdaFill(ds);
}
}
return ds;
}
}
}