封装SQLHelper
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GBYLibrary { class SQLHelper { static string connStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; /// <summary> /// 实现非查询操作,增删改返回受影响行数,否则返回-1 /// </summary> /// <param name="sql"></param> /// <param name="ps"></param> /// <returns></returns> public static int ExecuteNonQuary(string sql,params SqlParameter[] ps) { using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(ps); conn.Open(); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 首行查询 /// </summary> /// <param name="sql"></param> /// <param name="ps"></param> /// <returns></returns> public static object ExecuteScalar(string sql,params SqlParameter[] ps) { using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(ps); conn.Open(); return cmd.ExecuteScalar(); } } } public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] ps) { SqlConnection conn = new SqlConnection(connStr); 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; } } /// <summary> /// 获取DataSet离线数据集 /// </summary> /// <param name="sql"></param> /// <param name="ps"></param> /// <returns></returns> public static DataSet GetDataSet(string sql, params SqlParameter[] ps) { DataSet ds = new DataSet(); using (SqlDataAdapter sda = new SqlDataAdapter(sql, connStr))//创建DataAdapter数据适配器实例 { sda.SelectCommand.Parameters.AddRange(ps); sda.Fill(ds);//Fill()填充Da } return ds; } } }