Update()
GetSingleResult()
GetReader()
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data; 6 using System.Data.SqlClient; 7 using System.Configuration; 8 9 10 namespace DAL.Helper 11 { 12 public class SQLHelper 13 { 14 private static string connString = 15 ConfigurationManager.ConnectionStrings["sqlConnString"].ToString(); 16 17 #region 执行带参数SQL语句 18 /// <summary> 19 /// 执行增、删、改 Sql(Update、insert、delete)方法 20 /// </summary> 21 /// <param name="sql">提交的SQL语句,可以根据需要添加参数</param> 22 /// <param name="param">参数数组(如果没有参数,请传递null)</param> 23 /// <returns>返回受影响行数</returns> 24 public static int Update(string sql,SqlParameter[] param) 25 { 26 SqlConnection conn = new SqlConnection(connString); 27 SqlCommand cmd = new SqlCommand(sql, conn); 28 if(param != null) 29 { 30 cmd.Parameters.AddRange(param);//添加参数组 31 } 32 try 33 { 34 conn.Open(); 35 return cmd.ExecuteNonQuery(); 36 } 37 catch (Exception ex) 38 { 39 string info = "执行public static int Update"; 40 info += "(string sql,SqlParameter[] param)"+ex.Message; 41 throw new Exception(info); 42 } 43 finally 44 { 45 conn.Close(); 46 } 47 } 48 /// <summary> 49 /// 执行单一结果集查询 50 /// </summary> 51 /// <param name="sql">提交SQL语句,可根据需要添加参数</param> 52 /// <param name="param">参数数组,(如果没有参数、传递null)</param> 53 /// <returns>返回object对象</returns> 54 public static object GetSingleResult(string sql, SqlParameter[] param) 55 { 56 SqlConnection conn = new SqlConnection(connString); 57 SqlCommand cmd = new SqlCommand(sql, conn); 58 if(param != null) 59 { 60 cmd.Parameters.AddRange(param);//添加参数组; 61 } 62 try 63 { 64 conn.Open(); 65 return cmd.ExecuteScalar(); 66 } 67 catch (Exception ex) 68 { 69 string info = "执行public static object GetSingleResult"; 70 info += "(string sql, SqlParameter[] param)" + ex.Message; 71 throw new Exception(info); 72 } 73 finally 74 { 75 conn.Close(); 76 } 77 } 78 /// <summary> 79 /// 返回全部结果集查询 80 /// </summary> 81 /// <param name="sql"></param> 82 /// <param name="param"></param> 83 /// <returns></returns> 84 public static SqlDataReader GetReader(string sql,SqlParameter[] param) 85 { 86 SqlConnection conn = new SqlConnection(connString); 87 SqlCommand cmd = new SqlCommand(sql, conn); 88 if(param != null) 89 { 90 cmd.Parameters.AddRange(param);//添加参数组; 91 } 92 try 93 { 94 conn.Open(); 95 return cmd.ExecuteReader(CommandBehavior.CloseConnection); 96 } 97 catch (Exception ex) 98 { 99 string info = "public static SqlDataReader GetReader"; 100 info +="(string sql,SqlParameter[] param)"+ex.Message; 101 conn.Close(); 102 throw new Exception(info); 103 104 } 105 } 106 #endregion 107 108 109 110 111 112 113 114 } 115 }
原创地址:https://blog.csdn.net/qq_36482772/article/details/77987207
原文地址:https://www.cnblogs.com/RCJL/p/11994556.html
时间: 2024-11-05 20:43:36