using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace ConsoleApp5 { internal class DBHelper { private static string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; /// <summary> /// 增删改 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="param">是否带参数</param> /// <param name="isProc">是否是存储过程</param> public static void Update(string sql, List<SqlParameter> param, bool isProc) { using (SqlConnection con = new SqlConnection(conStr)) { con.Open(); using (SqlCommand cmd = new SqlCommand(sql, con)) { //判断是否有参数 if (param != null) { //批量添加 cmd.Parameters.AddRange(param.ToArray()); } //判断是否是存储过程 if (isProc) { cmd.CommandType = CommandType.StoredProcedure; } cmd.ExecuteNonQuery(); } } } /// <summary> /// 查询 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="param">是否带参数</param> /// <param name="isProc">是否是存储过程</param> public static DataTable Query(string sql, List<SqlParameter> param, bool isProc) { DataTable dt = new DataTable(); using (SqlConnection con = new SqlConnection(conStr)) { con.Open(); using (SqlCommand cmd = new SqlCommand(sql, con)) { //判断是否有参数 if (param != null) { //批量添加 cmd.Parameters.AddRange(param.ToArray()); } //判断是否是存储过程 if (isProc) { cmd.CommandType = CommandType.StoredProcedure; } using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(dt); } } } return dt; } public static object Scalar(string sql, List<SqlParameter> param, bool isProc) { object obj = null; using (SqlConnection con = new SqlConnection(conStr)) { con.Open(); using (SqlCommand cmd = new SqlCommand(sql, con)) { //判断是否有参数 if (param != null) { //批量添加 cmd.Parameters.AddRange(param.ToArray()); } //判断是否是存储过程 if (isProc) { cmd.CommandType = CommandType.StoredProcedure; } obj = cmd.ExecuteScalar(); } } return obj; } } }
标签:cmd,System,param,DBHelper,new,using,con From: https://www.cnblogs.com/kaede/p/16831800.html