ADO.NET的一个帮助类库
ADO NET的一个帮助类库 只须一个连接 一条SQL语句 轻松实现数据库的查旬 再加一个object 轻松实现数据库的增删改
该类库根据是否需要事务可分为两个部分 分别由三个构造方法决定
命名空间DBAssistant 类DBAssist
方法ExecNoQueryWithTran() 实现带事务的增删改 返回(int)影响的行数
方法 ExecNoQuery()实现不带事务的增删改 返回(int) 影响的行数
方法ExecScalar() 实现返回首行首列的查询 返回(object)
方法ExecSelect() 返回SqlDataReader
方法GetDataSet() 返回DataSet
using System;using System Collections Generic;using System Text;using System Data;using System Data SqlClient;using WriteException;namespace DBAssistant{public class DBAssist{/// <summary>/// 重载的构造方法/// </summary>public DBAssist() { }public DBAssist(string strSql SqlConnection conn){this StrSql = strSql;this Conn = conn;}public DBAssist(string strSql object obj SqlConnection conn){this StrSql = strSql;this Obj = obj;this Conn = conn;}public DBAssist(string strSql object obj SqlConnection conn SqlTransaction sqlTran){this StrSql = strSql;this Obj = obj;this Conn = conn;this sqlTran = 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)){cmd Transaction = sqlTran;num = cmd ExecuteNonQuery();//SqlTran Commit();}}catch (Exception ex){WriException Write(ex);//SqlTran Rollback();}return num;}/// <summary>/// 不带事务的增删改方法/// </summary>/// <returns>int</returns>public int ExecNoQuery(){int num = ;try{using (SqlCommand cmd = new SqlCommand(strSql conn)){num = cmd ExecuteNonQuery();}}catch (Exception ex){WriException Write(ex);}return num;}/// <summary>/// 返回 SqlDataReader 的查询方法/// </summary>/// <returns>SqlDataReader</returns>public SqlDataReader ExecSelect(){SqlDataReader dr = null;try{SqlCommand cmd = new SqlCommand(strSql conn);dr = cmd ExecuteReader(CommandBehavior CloseConnection);return dr;}catch (Exception ex){WriException Write(ex);}return null;}/// <summary>/// 调用ExecuteScalar()方法 返回 object 的查询方法/// </summary>/// <returns>Object</returns>public object ExecScalar(){count=null;try{using (SqlCommand cmd = new SqlCommand(strSql conn)){count = cmd ExecuteScalar();}}catch (Exception ex){WriException Write(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()){sda Fill(ds);}}return ds;}
}}
lishixinzhi/Article/program/net/201311/12853