public class SqlHelper { /// <summary> /// 获取连接字符串 /// </summary> static string conStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; #region ExecuteNonQuery /// <summary> /// 执行非查询语句,使用sql语句与参数化查询,返回受影响行数,如果执行的是非增删改语句返回-1 /// </summary> /// <param name="sql"></param> /// <param name="ps"></param> /// <returns></returns> public static int ExecuteNonQuery(string sql, params SqlParameter[] ps) { using (SqlConnection conn = new SqlConnection(conStr)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(ps); conn.Open(); return cmd.ExecuteNonQuery(); } } } #endregion #region ExecuteScalar /// <summary> /// 执行查询 返回的是首行首列 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="ps">sql三参数化数组</param> /// <returns></returns> public static object ExecuteScalar(string sql, params SqlParameter[] ps) { using (SqlConnection conn = new SqlConnection(conStr)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(ps); conn.Open(); return cmd.ExecuteScalar(); } } } #endregion #region ExecuteReader /// <summary> /// 按行读取数据 /// </summary> /// <param name="sql">sql语句</param> /// <param name="ps">参数</param> /// <returns></returns> public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] ps) { SqlConnection conn = new SqlConnection(conStr); try { using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(ps); conn.Open(); return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); } } catch (Exception ex) { conn.Dispose(); throw ex; } } #endregion #region SqlDataAdpter /// <summary> /// 取出数据集DataSet /// </summary> /// <param name="cmdText"></param> /// <param name="ps"></param> /// <returns></returns> public static DataSet GetDataSet(string cmdText, params SqlParameter[] ps) { DataSet ds = new DataSet(); using (SqlDataAdapter sda = new SqlDataAdapter(cmdText, connStr)) { sda.SelectCommand.Parameters.AddRange(ps); sda.Fill(ds); } return ds; } #endregion }