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 namespace DAL 10 { 11 public class SQLHelper 12 { 13 private static readonly string connstring = ConfigurationManager.ConnectionStrings["connString"].ToString(); 14 /// <summary> 15 /// 执行增、删、改操作 16 /// </summary> 17 /// <param name="sql">要执行的sql语句</param> 18 /// <param name="param">参数数组</param> 19 /// <returns>返回受影响的行数</returns> 20 public static int Update(string sql,SqlParameter[] param) 21 { 22 SqlConnection conn = new SqlConnection(connstring); 23 SqlCommand com = new SqlCommand(sql,conn); 24 if (param!=null) 25 { 26 com.Parameters.AddRange(param); 27 } 28 try 29 { 30 conn.Open(); 31 return com.ExecuteNonQuery(); 32 } 33 catch (Exception ex) 34 { 35 string info = "执行public static int Update(string sql,SqlParameter[] param)方法出错:" + ex.Message; 36 throw new Exception(info); 37 } 38 finally 39 { 40 conn.Close(); 41 } 42 } 43 /// <summary> 44 /// 执行返回单一结果及的方法 45 /// </summary> 46 /// <param name="sql">要执行的sql语句</param> 47 /// <param name="param">参数数值</param> 48 /// <returns>返回单一结果</returns> 49 public static object GetExecuteScalar(string sql, SqlParameter[] param) 50 { 51 SqlConnection conn = new SqlConnection(connstring); 52 SqlCommand com = new SqlCommand(sql, conn); 53 if (param!=null) 54 { 55 com.Parameters.AddRange(param); 56 } 57 try 58 { 59 conn.Open(); 60 return com.ExecuteScalar(); 61 } 62 catch (Exception ex) 63 { 64 string info = "执行 public static object GetExecuteScalar(string sql, SqlParameter[] param)方法出错:" + ex.Message; 65 throw new Exception(info); 66 } 67 finally 68 { conn.Close(); } 69 } 70 /// <summary> 71 /// 执行返回一个结果集 72 /// </summary> 73 /// <param name="sql">要执行的sql语句</param> 74 /// <param name="param">参数数组</param> 75 /// <returns>返回一个结果集合</returns> 76 public static SqlDataReader Get(string sql,SqlParameter[] param) 77 { 78 SqlConnection conn = new SqlConnection(connstring); 79 SqlCommand com = new SqlCommand(sql, conn); 80 if (param!=null) 81 { 82 com.Parameters.AddRange(param); 83 } 84 try 85 { 86 conn.Open(); 87 return com.ExecuteReader(CommandBehavior.CloseConnection); 88 } 89 catch (Exception ex) 90 { 91 string info = "执行public static SqlDataReader Get(string sql,SqlParameter[] param)方法出错" + ex.Message; 92 throw new Exception(info); 93 } 94 } 95 } 96 }