ADO.NET 对数据操作
1 public static class SQLHelper 2 { 3 static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString(); 4 /// <summary> 5 /// 执行增删改 6 /// </summary> 7 /// <param name="sql"></param> 8 /// <returns></returns> 9 public static int Update(string sql) 10 { 11 SqlConnection conn = new SqlConnection(connString); 12 SqlCommand cmd = new SqlCommand(sql, conn); 13 try 14 { 15 conn.Open(); 16 return cmd.ExecuteNonQuery(); 17 } 18 catch (Exception ex) 19 { 20 throw new Exception(ex.Message); 21 } 22 finally { 23 conn.Close(); 24 } 25 } 26 /// <summary> 27 /// 执行单一结果查询 28 /// </summary> 29 /// <param name="sql"></param> 30 /// <returns></returns> 31 public static object GetSingleResult(string sql) 32 { 33 SqlConnection conn = new SqlConnection(connString); 34 SqlCommand cmd = new SqlCommand(sql, conn); 35 try 36 { 37 conn.Open(); 38 return cmd.ExecuteScalar(); 39 } 40 catch (Exception ex) 41 { 42 throw new Exception(ex.Message); 43 } 44 finally 45 { 46 conn.Close(); 47 } 48 } 49 50 /// <summary> 51 /// 执行一个结果集查询 52 /// </summary> 53 /// <param name="sql"></param> 54 /// <returns></returns> 55 public static SqlDataReader GetReader(string sql) 56 { 57 SqlConnection conn = new SqlConnection(connString); 58 SqlCommand cmd = new SqlCommand(sql, conn); 59 try 60 { 61 conn.Open(); 62 return cmd.ExecuteReader(CommandBehavior.CloseConnection); 63 } 64 catch (Exception ex) 65 { 66 conn.Close(); 67 throw new Exception(ex.Message); 68 } 69 } 70 }
View Code