首页 > 代码库 > 封装SQLHelper
封装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; } } }
封装SQLHelper
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。