public class SQLHelperNew { //连接字符串 private static readonly string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; /// <summary> /// 返回SqlDataReader /// </summary> /// <param name="sql">连接字符串</param> /// <param name="cmdParms">CMD参数集合</param> /// <returns></returns> public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] cmdParms) { using (SqlConnection con = new SqlConnection(ConnStr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); if (cmdParms.Count() > 0) { cmd.Parameters.AddRange(cmdParms); } try { return cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { con.Close(); cmd.Dispose(); } } } } /// <summary> /// 返回数据表 /// </summary> /// <param name="sql">连接字符串</param> /// <param name="cmdParms">CMD参数集合</param> /// <returns></returns> public static DataTable ExecuteDataTable(string sql, params SqlParameter[] cmdParms) { using (SqlConnection con = new SqlConnection(ConnStr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { DataTable dt = new DataTable(); if (cmdParms.Count() > 0) { cmd.Parameters.AddRange(cmdParms); } try { con.Open(); SqlDataAdapter rd = new SqlDataAdapter(cmd); rd.Fill(dt); return dt; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { con.Close(); cmd.Dispose(); } } } } /// <summary> /// 返回受影响的行数 /// </summary> /// <param name="sql">连接字符串</param> /// <param name="cmdParms">CMD参数集合</param> /// <returns></returns> public static int ExecuteNonQuery(string sql, params SqlParameter[] cmdParms) { using (SqlConnection con = new SqlConnection(ConnStr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); if (cmdParms.Count() > 0) { cmd.Parameters.AddRange(cmdParms); } try { return cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { con.Close(); cmd.Dispose(); } } } } /// <summary> /// 返回首行首列 /// </summary> /// <param name="sql">连接字符串</param> /// <param name="cmdParms">CMD参数集合</param> /// <returns></returns> public static object ExecuteScalar(string sql, params SqlParameter[] cmdParms) { using (SqlConnection con = new SqlConnection(ConnStr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); if (cmdParms.Count() > 0) { cmd.Parameters.AddRange(cmdParms); } try { return cmd.ExecuteScalar(); } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { con.Close(); cmd.Dispose(); } } } } } }