using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data.SqlClient; using System.Data; namespace progressdemo.DAL { public static class SQLHelper { //获得配置文件中的连接字符串 private static readonly string constr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; /// <summary> /// 执行insert、delete、update的方法 /// </summary> /// <param name="sql"></param> /// <param name="pms"></param> /// <returns></returns> public static int ExecteNonQuery(string sql, params SqlParameter[] pms) { //sqlconnection 表示连接数据库 using (SqlConnection con=new SqlConnection(constr)) { using (SqlCommand cmd=new SqlCommand(sql,con)) { if (pms!=null) { cmd.Parameters.AddRange(pms); } con.Open(); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 返回首行首列 /// </summary> /// <param name="sql"></param> /// <param name="pms"></param> /// <returns></returns> public static object ExecuteScalar(string sql,params SqlParameter[] pms) { using (SqlConnection con=new SqlConnection(constr)) { using (SqlCommand cmd=new SqlCommand(sql,con)) { if (pms!=null) { cmd.Parameters.AddRange(pms); } con.Open(); return cmd.ExecuteScalar(); } } } public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms) { SqlConnection con=new SqlConnection(constr); try { using (SqlCommand cmd=new SqlCommand(sql,con)) { if (pms != null) { cmd.Parameters.AddRange(pms); } con.Open(); //当调用ExecuteReader的时候如果传递的CommandBehavior.CloseConnection参数当reader关闭的时候 //sqlconnection也被关闭 SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return reader; } }catch{ if(con!=null){ con.Close();con.Disponse();
}
throw; } } public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms) { SqlDataAdapter sqlAdaper = new SqlDataAdapter(sql, constr); if (pms!=null) { sqlAdaper.SelectCommand.Parameters.AddRange(pms); } DataTable dt = new DataTable(); sqlAdaper.Fill(dt); return dt; } } }