四大天王变形金刚(SqlHelper)

  1、的基础上推出  

SqlHelper是一个基于·NET Framework的数据库操作组件。组件中包括数据库操作方法。SqlHelper用于简化你反复的去写那些数据库连接(SqlConnection),SqlCommand,SqlDataReader等等。SqlHelper 封装过后一般是仅仅须要给方法传入一些參数如数据库连接字符串。SQL參数等。就能够訪问数据库了。非常方便。

简单的讲,就是将“四大天王”中具有共性的东西。封装起来,从而让我们的代码变得简单,易于扩展。

  2、实现方法(Vb.Net版)

(1)</strong>配制文件(U层)

在建立的应用窗口项目下。有一个App.Config文件,打开,然后在</startup>后边加入例如以下代码

<span style="font-size:18px;">  <appSettings>
    <clear/>
    <add key="ConnStr" value="server=localhost;Database=Login;User=sa;Password=123456;"/>
  </appSettings></span>

加入完以后,例如以下图

<span style="font-size:18px;"><?

xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

  <appSettings>
    <clear/>
    <add key="ConnStr" value="server=localhost;Database=Login;User=sa;Password=123456;"/>
  </appSettings>

</configuration></span>

         其它方法另外參照VB.Net—配置文件

 
       
(2)实现SqlHelper类

<span style="font-size:18px;">Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration          '加入必要引用

Public Class SqlHelper

    '定义变量
    '获得数据库链接字符串
    Private ReadOnly strConnection As String = ("ConnStr")
    '设置链接
    Dim conn As SqlConnection = New SqlConnection(strConnection)
    '定义Command命令
    Dim cmd As New SqlCommand

    ' <summary>
    ' 运行增删改三个操作,(有參)返回值为Boolean类型,确认是否运行成功
    ' </summary>
    ' <param name="cmdText">须要运行语句,通常是Sql语句,也有存储过程</param>
    ' <param name="cmdType">推断Sql语句的类型,一般都不是存储过程</param>
    ' <param name="paras">參数数组,无法确认有多少參数</param>
    ' <returns></returns>
    ' <remarks></remarks>
    Public Function ExecAddDelUpdate(ByVal cmdText As String, ByVal cmdType As CommandType, ByVal paras As SqlParameter()) As Integer

        '将传入的值,分别为cmd的属性赋值
        cmd.Parameters.AddRange(paras)        '将參数传入
        cmd.CommandType = cmdType             '设置一个值,解释cmdText
        cmd.Connection = conn                 '设置连接,全局变量
        cmd.CommandText = cmdText             '设置SQL语句

        Try
            conn.Open()                       '打开链接
            Return cmd.ExecuteNonQuery()      '运行增删改操作
            cmd.Parameters.Clear()            '清除參数
        Catch ex As Exception
            Return 0                          '假设出错就返回0
        Finally
            Call CloseConn(conn)
            Call CloseCmd(cmd)
        End Try
    End Function

    ' <summary>
    ' 运行增删改三个操作,(无參)
    ' </summary>
    ' <param name="cmdText">须要运行语句,通常是Sql语句,也有存储过程</param>
    ' <param name="cmdType">推断Sql语句的类型,一般都不是存储过程</param>
    ' <returns>Interger,受影响的行数</returns>
    ' <remarks>2013年2月2日8:19:59</remarks>   

    Public Function ExecAddDelUpdateNo(ByVal cmdText As String, ByVal cmdType As CommandType) As Integer

        '为要运行的命令cmd赋值
        cmd.CommandText = cmdText               '传入查询语句
        cmd.CommandType = cmdType               '设置Sql语句怎样解释
        cmd.Connection = conn                   '设置连接

        '运行操作
        Try
            conn.Open()
            Return cmd.ExecuteNonQuery
        Catch ex As Exception
            Return 0
        Finally
            Call CloseConn(conn)
            Call CloseCmd(cmd)
        End Try

    End Function
    ' <summary>
    ' 运行查询的操作,(有參),參数不限
    ' </summary>
    ' <param name="cmdText">须要运行语句,通常是Sql语句,也有存储过程</param>
    ' <param name="cmdType">推断Sql语句的类型,一般都不是存储过程</param>
    ' <param name="paras">传入的參数</param>
    ' <returns></returns>
    ' <remarks></remarks> 

    Public Function ExecSeletct(ByVal cmdText As String, ByVal cmdType As CommandType, ByVal paras As SqlParameter()) As DataTable

        Dim sqlAdpter As SqlDataAdapter            '是 DataSet和 SQL Server之间的桥接器,用于检索和保存数据
        Dim dt As New DataTable
        Dim ds As New DataSet

        '还是给cmd赋值
        cmd.CommandText = cmdText                  '设置查询语句
        cmd.CommandType = cmdType                  '设置Cmd对象的类型
        cmd.Connection = conn                      '数据库连接语句
        cmd.Parameters.AddRange(paras)             '传入參数
        sqlAdpter = New SqlDataAdapter(cmd)        '实例化适配器

        Try
            sqlAdpter.Fill(ds)                     '用adapter将dataSet填充
            dt = ds.Tables(0)                      'dataTable是dataSet的第一个表
            cmd.Parameters.Clear()                 '清除參数
        Catch ex As Exception
            MsgBox("查询失败", CType(vbOKOnly + MsgBoxStyle.Exclamation, MsgBoxStyle), "警告。")
        Finally
            Call CloseCmd(cmd)                     '最后一定要释放cmd
        End Try

        Return dt      '返回查到的数据

    End Function

    ' <summary>
    ' 运行查询的操作,(无參)
    ' </summary>
    ' <param name="cmdText">须要运行语句,通常是Sql语句,也有存储过程</param>
    ' <param name="cmdType">推断Sql语句的类型,一般都不是存储过程</param>
    ' <returns>dataTable,查询到的表格</returns>
    ' <remarks></remarks>   

    Public Function ExecSelectNo(ByVal cmdText As String, ByVal cmdType As CommandType) As DataTable

        Dim sqlAdapter As SqlDataAdapter
        Dim ds As New DataSet

        '给cmd赋值
        cmd.CommandText = cmdText
        cmd.CommandType = cmdType
        cmd.Connection = conn

        sqlAdapter = New SqlDataAdapter(cmd)         '实例化适配器

        Try
            sqlAdapter.Fill(ds)                      '用adapter将dataSet填充
            Return ds.Tables(0)                      '返回dataSet的第一个表
        Catch ex As Exception
            Return Nothing
        Finally
            Call CloseCmd(cmd)                       '关闭cmd
        End Try

    End Function

    ' <summary>
    ' 关闭连接
    ' </summary>
    ' <param name="conn">须要关闭的连接</param>
    ' <remarks></remarks>   

    Public Sub CloseConn(ByVal conn As SqlConnection)

        If (conn.State <> ConnectionState.Closed) Then  '假设没有关闭
            conn.Close()                                '关闭连接
            conn = Nothing                              '不指向原对象
        End If

    End Sub

    ' <summary>
    ' 关闭命令
    ' </summary>
    ' <param name="cmd">须要关闭的命令</param>
    ' <remarks></remarks>    

    Public Sub CloseCmd(ByVal cmd As SqlCommand)

        If Not IsNothing(cmd) Then                      '假设cmd命令还存在
            cmd.Dispose()                               '释放资源
            cmd = Nothing                               '不指向原对象
        End If

    End Sub

End Class
</span>

版权声明:本文博客原创文章。博客,未经同意,不得转载。

时间: 2024-08-28 17:35:13

四大天王变形金刚(SqlHelper)的相关文章

四大天王之变形金刚(SqlHelper)

</pre>        1.基础介绍<p></p><p><span style="color:rgb(51,51,51); font-family:arial,宋体,sans-serif; line-height:24px; text-indent:28px"><span style="font-size:18px">        SqlHelper是一个基于·NET Framework的

【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