one pragmatical sqlhelper

namespace ConsoleApplication2
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;

    public class SqlHelper
    {
        /// <summary>
        /// 连接字符串
        /// </summary>ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;
        /// <summary>
        /// 准备Command对象
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns></returns>
        private static SqlCommand PrepareCommand(string sql, params SqlParameter[] spms)
        {
            SqlConnection conn = new SqlConnection(strConn);
            SqlCommand cmd = new SqlCommand(sql, conn);
            if (spms != null)
                cmd.Parameters.AddRange(spms);
            return cmd;
        }
        /// <summary>
        /// 提交sql语句执行(增删改)
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns>影响行数</returns>
        public static int ExecuteNonQuery(string sql, params SqlParameter[] spms)
        {
            int result = 0;
            SqlCommand cmd = PrepareCommand(sql, spms);
            try
            {
                cmd.Connection.Open();
                result = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
                throw new Exception(ex.Message);
            }
            finally
            {
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
            }
            return result;
        }
        /// <summary>
        /// 提交sql语句返回首行首列的值
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string sql, params SqlParameter[] spms)
        {
            object result = null;
            SqlCommand cmd = PrepareCommand(sql, spms);
            try
            {
                cmd.Connection.Open();
                result = cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
                throw new Exception(ex.Message);
            }
            finally
            {
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
            }
            return result;
        }
        /// <summary>
        /// 提交sql语句执行(增删改),bayistuta新增,2011/03/21 17:13
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns>影响行数</returns>
        public static int ExecuteNonQuery(string sql, CommandType type, params SqlParameter[] spms)
        {
            int result = 0;
            SqlCommand cmd = PrepareCommand(sql, spms);
            cmd.CommandType = type;
            try
            {
                cmd.Connection.Open();
                result = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
                throw new Exception(ex.Message);
            }
            finally
            {
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
            }
            return result;
        }
        /// <summary>
        /// 提交sql语句返回读取器,bayistuta新增,2011/03/25 21:26
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string sql, CommandType type, params SqlParameter[] spms)
        {
            SqlDataReader reader = null;
            SqlCommand cmd = PrepareCommand(sql, spms);
            cmd.CommandType = type;
            try
            {
                cmd.Connection.Open();
                //关闭reader对象,其对应的连接对象自动关闭
                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                if (reader != null)
                    reader.Close();
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
                throw new Exception(ex.Message);
            }
            return reader;
        }
        /// <summary>
        /// 提交sql语句返回读取器
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] spms)
        {
            SqlDataReader reader = null;
            SqlCommand cmd = PrepareCommand(sql, spms);
            try
            {
                cmd.Connection.Open();
                //关闭reader对象,其对应的连接对象自动关闭
                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                if (reader != null)
                    reader.Close();
                if (cmd.Connection.State != ConnectionState.Closed)
                    cmd.Connection.Close();
                throw new Exception(ex.Message);
            }
            return reader;
        }
        /// <summary>
        /// 查询实体类对象集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns></returns>
        public static List<T> GetList<T>(string sql, params SqlParameter[] spms)
        {
            List<T> list = new List<T>();
            SqlDataReader reader = ExecuteReader(sql, spms);
            while (reader.Read())
            {
                T t = CreateInstance<T>(reader);
                list.Add(t);
            }
            reader.Close();
            return list;
        }
        /// <summary>
        /// 查询单个实体类对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns></returns>
        public static T GetSingle<T>(string sql, params SqlParameter[] spms)
        {
            T t = default(T);
            SqlDataReader reader = ExecuteReader(sql, spms);
            if (reader.Read())
            {
                t = CreateInstance<T>(reader);
            }
            reader.Close();
            return t;
        }

        /// <summary>
        /// 返回DataTable
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="spms">参数</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql, params SqlParameter[] spms)
        {
            SqlCommand cmd = PrepareCommand(sql, spms);

            SqlDataAdapter da = new SqlDataAdapter(cmd); //创建DataAdapter数据适配器实例
            DataSet ds = new DataSet();//创建DataSet实例
            da.Fill(ds, "tables");//使用DataAdapter的Fill方法(填充),调用SELECT命令
            if (cmd.Connection.State != ConnectionState.Closed)
                cmd.Connection.Close();
            return ds.Tables[0];
        }
        /// <summary>
        /// 返回DataTable
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="spms">参数</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql, CommandType cmdType, params SqlParameter[] spms)
        {
            SqlCommand cmd = PrepareCommand(sql, spms);
            cmd.CommandType = cmdType;
            SqlDataAdapter da = new SqlDataAdapter(cmd); //创建DataAdapter数据适配器实例
            DataSet ds = new DataSet();//创建DataSet实例
            da.Fill(ds, "tables");//使用DataAdapter的Fill方法(填充),调用SELECT命令
            if (cmd.Connection.State != ConnectionState.Closed)
                cmd.Connection.Close();
            return ds.Tables[0];
        }
        /// <summary>
        /// 查询记录条数
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="spms"></param>
        /// <returns></returns>
        public static int GetCount(string sql, params SqlParameter[] spms)
        {
            return (int)ExecuteScalar(sql, spms);
        }
        /// <summary>
        /// 使用反射根据实体类的构造函数创建实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        private static T CreateInstance<T>(IDataReader reader)
        {
            Type type = typeof(T);
            T t = (T)Activator.CreateInstance(type, reader);
            return t;
        }

        /// <summary>
        /// 防sql注入,替换字符串
        /// </summary>
        /// <param name="val">需要替换的值</param>
        /// <returns>替换后的值</returns>
        public static string GetParameterValue(string val)
        {
            return val.Replace("‘", "‘‘").Replace("-", "[-]");
        }
    }

}

  

时间: 2024-10-10 16:51:54

one pragmatical sqlhelper的相关文章

【2016-11-2】【坚持学习】【Day17】【微软 推出的SQLHelper】

从网络上找到 微软原版本的SQLHelper,很多行代码.认真看了,学习了. 代码: 1 using System; 2 using System.Data; 3 using System.Xml; 4 using System.Data.SqlClient; 5 using System.Collections; 6 7 namespace Helper 8 { 9 /// <summary> 10 /// The SqlHelper class is intended to encapsu

对SqlHelper的理解

简介 Sqlhelper 是用来避免重复输入连接数据库代码的类,封装后只需要给类中的方法传入一些参数如数据库连接字符串,SQL参数等就可以访问数据库了.因为我们要声明该类不能被继承或实例化,所以我们要通过静态方法来封装数据访问功能.静态方法为类所有,可以通过对象来使用,也可以通过类来使用.但一般提倡通过类名来使用,应为静态方法只要定义了类,不必建立类的实例就可使用. 机制 上面说了SqlHelper的简介,接下来介绍它具体的运行机制.首先和普通连接数据库的步骤一样,要先定义Connection对

机房收费系统中sqlhelper的应用

在接受了三层的思想之后,sqlhelper被传的沸沸扬扬,它给我们的编码带来多少优势.让编码者少花了多少时间.多少精力,等等的赞美之词不绝于耳.自己也是将信将疑的,毕竟自己没有亲身经历,所以没有很大的体会.而如今,自己多次使用了sqlhelper,穿梭在各层之间确实也体会到了它带给我们的简便之处,结合很多人的版本自己编写了属于自己的那一版,以下便是具体代码: <span style="font-family:KaiTi_GB2312;font-size:18px;">Imp

公共的数据库访问访问类 SqlHelper.cs

/// <summary> /// 类说明:公共的数据库访问访问类 /// </summary> using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Collections; namespace DotNet.Utilities { /// <summary> /// 

DapperHelper,SqlHelper

using System;using System.Collections.Generic;using System.Data.Common;using System.Linq;using System.Text;using System.Threading.Tasks;using Dapper;using System.Configuration;using System.Data.SqlClient;using System.Data; namespace OADemo.Tool{ publ

SqlHelper中IN集合场景下的参数处理

我手头有个古老的项目,持久层用的是古老的ADO.net.前两天去昆明旅游,其中的一个景点是云南民族村,通过导游介绍知道了一个古老的民族——基诺族,这是我国的第56个民族.  项目里的ado.net和基诺族一样古老. 话说,项目里数据访问层,好多都是拼的sql,这给sql注入提供了可乘之机,为了系统安全,决定在有限的时间内,将它改成参数化. 其中,有个根据多个订单号查询支付单的方法,签名如下: public DataTable GetAlipayNotifyRecords(AlipayPaymen

C#实现较为实用的SQLhelper

第一次写博客,想不到写什么好b( ̄▽ ̄)d ,考虑的半天决定从sqlhelper开始,sqlhelper对程序员来说就像helloworld一样,很简单却又很重要,helloworld代表着程序员萌新第一次写代码,而sqlhelper则是初次接触数据库(不知道这种说法对不对). 好了不废话了,下面直接上代码(无话可说了): 1 public class SQLHelper 2 { 3 // 超时时间 4 private static int Timeout = 1000; 5 // 数据库名称

微软原版SQLHelper类

C# Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

微软SQLHelper.cs类 中文版

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Xml; using System.Collections; namespace LiuYanBanT { public class SqlHelper