前几年一直在用很老的SqlHelper。但百度发现现在有好多新的SqlHelper了。近几年一直在捣腾web前端,ADO都差不多忘光了。谢谢大神帮忙看下小弟的SqlHelper有没有问题,需不需要改进下。
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace mipopoWeb.DAL { public class Sqlhelper { /// <summary> /// 创建连接对象 /// </summary> /// <returns></returns> public static SqlConnection GetConnection() { string name = ConfigurationManager.ConnectionStrings["dbStr"].ToString(); return new SqlConnection(name); } /// <summary> /// 查询第一行第一列 /// </summary> /// <param name="sql">执行的SQL语句</param> /// <param name="param">参数数组</param> /// <returns></returns> public static object ExecuteScalar(string sql, params SqlParameter[] param) { using (SqlConnection conn = GetConnection()) { SqlCommand comm = new SqlCommand(sql, conn); if (param != null) { comm.Parameters.AddRange(param); } conn.Open(); object obj = comm.ExecuteScalar(); return obj; } } /// <summary> /// 查询(整张表) /// </summary> /// <param name="sql">执行的SQL语句</param> /// <param name="param">参数数组</param> /// <returns></returns> public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] param) { SqlConnection conn = GetConnection(); SqlCommand comm = new SqlCommand(sql, conn); if (param != null) { comm.Parameters.AddRange(param); } conn.Open(); SqlDataReader obj = comm.ExecuteReader(CommandBehavior.CloseConnection); return obj; } /// <summary> /// 增删改 /// </summary> /// <param name="sql">执行的SQL语句</param> /// <param name="param">参数数组</param> /// <returns></returns> public static int ExecuteNonQuery(string sql, params SqlParameter[] param) { using (SqlConnection conn = GetConnection()) { SqlCommand comm = new SqlCommand(sql, conn); if (param != null) { comm.Parameters.AddRange(param); } conn.Open(); int obj = comm.ExecuteNonQuery(); return obj; } } /// <summary> /// 返回DataTable /// </summary> /// <param name="sql">执行的SQL语句</param> /// <returns></returns> public static DataTable FillTable(string sql) { SqlDataAdapter adapter = new SqlDataAdapter(sql, GetConnection()); DataTable dt = new DataTable(); adapter.Fill(dt); return dt; } } }
还是用dapper好一些,轻量级
研究下dapper
https://github.com/wrx362114/EasyDAL
一个dal层自动生成的模版项目.
最近再研究dapper,打算换掉项目中的sqlhelper