日期:2014-05-18 浏览次数:20883 次
public class MSSQLDAL:IDataAccess { private SqlConnection _con; private SqlTransaction _tran; public MSSQLDAL(string constr) { this._con = new SqlConnection(constr); } #region IDataAccess 成员 /// <summary> /// 打开数据库连接 /// </summary> public void Open() { try { if (this._con == null || this._con.State == ConnectionState.Closed) { this._con.Open(); } else { this._con.Close(); this._con.Open(); } } catch { this._con.Close(); } } /// <summary> /// 关闭数据库连接 /// </summary> public void Close() { if (this._con != null || this._tran != null) { this._con.Close(); } } /// <summary> /// 增删改操作 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="param">参数</param> /// <returns>影响行数</returns> public int ExecuteNonQuery(string sql, params QueryParameter[] param) { int i = 0; try { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, sql, CommandType.Text, param); i = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } catch { this._con.Close(); } return i; } /// <summary> /// 返回单个值 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="param">参数</param> /// <returns>查询结果的第一行值</returns> public object GetScalar(string sql, params QueryParameter[] param) { object obj = null; try { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, sql, CommandType.Text, param); obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); } catch { this._con.Close(); } return obj; } /// <summary> /// 返回DataTable /// </summary> /// <param name="sql">SQL语句</param> /// <param name="param">参数</param> /// <returns>DataTable</returns> public DataTable GetDataTable(string sql, params QueryParameter[] param) { DataTable dt = new DataTable(); try { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, sql, CommandType.Text, param); SqlDataAdapter da = new SqlDataAdapter(cmd); dt = new DataTable(); da.Fill(dt); cmd.Parameters.Clear(); } catch { this._con.Close(); } return dt; } /// <summary> /// 返回DataReader /// </summary> /// <param name="sql">SQL语句</param> /// <param name="param">参数</param> /// <returns>DataReader</returns> public IDataReader GetDataReader(string sql, params QueryParameter[] param) { SqlDataReader dr = null;