在我们编写数据访问层DAL时,常常需要编写一个SQLHelper类,方便其他的数据库表类调用,下面就是一个实现了可以传递sql语句来增删改查得类:
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.Data; using System.Configuration; namespace DAL { public class SQLHelper { private SqlConnection conn = null; private SqlCommand comm = null; private SqlDataReader sdr = null; public SQLHelper() { string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; conn = new SqlConnection(connStr); } private SqlConnection GetConn() { if (conn.State == ConnectionState.Closed) { conn.Open(); } return conn; } /// <summary> /// 执行不带sql参数的增删改sql语句或存储过程 /// </summary> /// <param name="cmdText">增删改sql语句或存储过程</param> /// <param name="ct">命令类型</param> /// <returns></returns> public int ExecuteNonQuery(string cmdText, CommandType ct) { using (comm = new SqlCommand(cmdText,GetConn())) { comm.CommandType = ct; int res = comm.ExecuteNonQuery(); return res; } } /// <summary> /// 执行带有sql参数的增删改sql语句或存储过程 /// </summary> /// <param name="cmdText">sql语句或者存储过程</param> /// <param name="paras">sql语句参数或存储过程参数</param> /// <param name="ct">命令类型</param> /// <returns></returns> public int ExecuteNonQuery(string cmdText, SqlParameter[] paras, CommandType ct) { using (comm = new SqlCommand(cmdText,GetConn())) { comm.CommandType = ct; comm.Parameters.AddRange(paras); int res = comm.ExecuteNonQuery(); return res; } } /// <summary> /// 执行不带sql参数的sql查询语句或存储过程 /// </summary> /// <param name="cmdText">sql查询语句或存储过程</param> /// <param name="ct">命令类型</param> /// <returns>数据表</returns> public DataTable ExecuteQuery(string cmdText,CommandType ct) { comm = new SqlCommand(cmdText, GetConn()); comm.CommandType = ct; DataTable dt = new DataTable(); using (sdr = comm.ExecuteReader(CommandBehavior.CloseConnection)) { dt.Load(sdr); } return dt; } /// <summary> /// 执行带有sql参数的sql查询语句或存储过程 /// </summary> /// <param name="cmdText">sql查询语句或存储过程</param> /// <param name="paras">sql参数</param> /// <param name="ct">命令类型</param> /// <returns>数据表</returns> public DataTable ExcuteQuery(string cmdText, SqlParameter[] paras, CommandType ct) { comm = new SqlCommand(cmdText, GetConn()); comm.CommandType = ct; comm.Parameters.AddRange(paras); DataTable dt = new DataTable(); using (sdr = comm.ExecuteReader(CommandBehavior.CloseConnection)) { dt.Load(sdr); } return dt; } } }