封装SQLHelper

Posted 影落明湖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装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的主要内容,如果未能解决你的问题,请参考以下文章

封装SQLHelper

封装sqlhelper

关于SqlHelper的详解

SqlHelper

数据库2_sqlHelper

VSCode自定义代码片段14——Vue的axios网络请求封装