C# 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 FirstBI
{
    public abstract class SqlHelpertrain//定义为abstract抽象类,不能被实例化,在应用时直接调用
    {
        /*1.获取数据库连接字符串;
         * 2.Connection 链接绑定,open/close;
         * 3.实例化一个Command命令,给定命令执行的超时时间 ,命令执行的连接;命令的类型(增/删/改/查)
         *      ,是否带事务,执行用到哪些参数,还有最重要的命令执行的sql字符串;
         * 4.SqlDataAdapter承接命令返回的结果集
         */
        private static int TimeOut = 5000;
        private static string connStrs = ConfigurationManager.ConnectionStrings["FirstBI.Properties.Settings.BaseERPConnectionString"].ConnectionString;
        /// <summary>
        /// 获取SqlCommand
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="cmdType"></param>
        /// <param name="tran"></param>
        /// <param name="sqlParams"></param>
        /// <returns></returns>
        public static SqlCommand GetSqlCommand(string sql, SqlConnection conn, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.CommandTimeout = TimeOut;
            cmd.CommandType = cmdType;
            if (tran != null)
                cmd.Transaction = tran;
            if (sqlParams != null && sqlParams.Length > 0)
                cmd.Parameters.AddRange(sqlParams);
            return cmd;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdType"></param>
        /// <param name="tran"></param>
        /// <param name="sqlParams"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams)
        {
            using (SqlConnection conn = new SqlConnection(connStrs))
            {
                try
                {
                    conn.Open();
                    using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams))
                    {
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            DataTable dt = new DataTable();
                            da.Fill(dt);
                            return dt;
                        }
                    }

                }
                catch (SqlException ex)
                {
                    StringBuilder log = new StringBuilder();
                    log.Append("查询数据错误:");
                    log.Append(ex);
                    throw new Exception(log.ToString());
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdType"></param>
        /// <param name="tran"></param>
        /// <param name="sqlParams"></param>
        /// <returns></returns>
        public static DataSet GetDataSet(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams)
        {
            using (SqlConnection conn = new SqlConnection(connStrs))
            {
                using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams))
                {
                    try
                    {
                        conn.Open();
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            return ds;
                        }
                    }
                    catch (SqlException ex)
                    {
                        StringBuilder log = new StringBuilder();
                        log.Append("查询数据错误:");
                        log.Append(ex);
                        throw new Exception(log.ToString());
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdType"></param>
        /// <param name="tran"></param>
        /// <param name="sqlParams"></param>
        /// <returns></returns>
        public static int ExecNonQuery(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams)
        {
            /*定义: SqlCommand cmd = new SqlCommand();//或者SqlCommand cmd = new SqlConnection().CreateCommand(); 注意参数
                cmd.CommandType = CommandType.StoredProcedure; //存储过程
                cmd.CommandType = CommandType.Text; //sql语句
                cmd.CommandType = CommandType.TableDirect; System.Data.CommandType.TableDirect表示要执行的是表
                    ,此时,cmd.CommandText 的值应该是要查询表的的名称。查询结果返回的是整个表。
             */
            int count = 0;
            using (SqlConnection conn = new SqlConnection(connStrs))
            {
                using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams))
                {

                    try
                    {
                        conn.Open();

                        if (cmdType == CommandType.StoredProcedure)
                            cmd.Parameters.AddWithValue("@RETURN_VALUE", "").Direction = ParameterDirection.ReturnValue;
                        count = cmd.ExecuteNonQuery();
                        if (count <= 0)
                            if (cmdType == CommandType.StoredProcedure)
                                count = (int)cmd.Parameters["@RETURN_VALUE"].Value;
                    }
                    catch (SqlException ex)
                    {
                        StringBuilder log = new StringBuilder();
                        log.Append("查询数据错误:");
                        log.Append(ex);
                        throw new Exception(log.ToString());
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return count;
        }
        public static object QueryScalar(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams)
        {
            using (SqlConnection conn = new SqlConnection(connStrs))
            {
                using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams))
                {
                    try
                    {
                        conn.Open();//创建cmd之前或之后Open都是可以的
                        return cmd.ExecuteScalar();
                    }
                    catch (SqlException ex)
                    {
                        StringBuilder log = new StringBuilder();
                        log.Append("查询数据出错:");
                        log.Append(ex);
                        throw new Exception(log.ToString());
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdType"></param>
        /// <param name="tran"></param>
        /// <param name="sqlParams"></param>
        /// <returns></returns>
        public static SqlDataReader GetDataReader(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams)
        {
            //SqlDataReader要求,它读取数据的时候有,它独占它的SqlConnection对象,而且SqlConnection必须是Open状态
            //SqlDataReader与SqlDataAdapter的区别:SqlDataReader为在线操作数据库,SqlDataAdapter为离线操作(打开连接获取数据集之后关闭连接,然后离线操作数据库,然后再打开连接将数据更新到数据库)
            using (SqlConnection conn = new SqlConnection(connStrs))
            {
                using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams))
                {
                    try
                    {
                        conn.Open();
                        //CommandBehavior.CloseConnection当SqlDataReader释放的时候,顺便把SqlConnection对象也释放掉
                        return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    }
                    catch (SqlException ex)
                    {
                        StringBuilder log = new StringBuilder();
                        log.Append("查询数据错误:");
                        log.Append(ex);
                        throw new Exception(log.ToString());
                    }
                }
            }
        }
    }
}

原文地址:https://www.cnblogs.com/allen0/p/9495565.html

时间: 2024-08-29 17:55:35

C# 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

分享一个简单的简单的SQLHelper类

分享一个简单的简单的SQLHelper类,代码如下: 1 class SqlHelper 2 { 3 public static readonly string connstr = 4 ConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString; 5 6 public static int ExecuteNonQuery(string cmdText, 7 params SqlParameter[] para