【ASP.Net】Pet Shop4.0学习笔记1(VB)

   2023-02-09 学习力0
核心提示:最近在学ASP.Net,在网上找了许久也没找到VB版的Pet Shop,只好下了C#的自己翻译,就当熟悉C#语法了。Imports SystemImports System.DataImports System.Data.SqlClientImports System.ConfigurationImports System.ComponentModelNamespace PetShop.DBU
最近在学ASP.Net,在网上找了许久也没找到VB版的Pet Shop,只好下了C#的自己翻译,就当熟悉C#语法了。
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.ComponentModel

Namespace PetShop.DBUtility

    
''' <summary>
    ''' The SqlHelper class is intended to encapsulate high performance, 
    ''' scalable best practices for common uses of SqlClient.
    ''' </summary>
    Public MustInherit Class SQLHelper

        
'Database connection strings
        Public Shared ReadOnly ConnectionStringLocalTransaction As String = ConfigurationManager.ConnectionStrings("SQLConnString1").ConnectionString
        
Public Shared ReadOnly ConnectionStringInventoryDistributedTransaction = ConfigurationManager.ConnectionStrings("SQLConnString2").ConnectionString
        
Public Shared ReadOnly ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings("SQLConnString3").ConnectionString
        
Public Shared ReadOnly ConnectionStringProfile = ConfigurationManager.ConnectionStrings("SQLProfileConnString").ConnectionString

        
'Hashtable to store cached parameters
        Private Shared parmCache As Hashtable = Hashtable.Synchronized(New Hashtable)

        
'''<summary>
        '''Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        '''using the provided parameters.
        '''</summary>
        '''<remarks>
        '''e.g.:  
        ''' int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        '''</remarks>
        '''<param name="connectionString">a valid connection string for a SqlConnection</param>
        '''<param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
        '''<param name="cmdText">the stored procedure name or T-SQL command</param>
        '''<param name="commandParameters">an array of SqlParamters used to execute the command</param>
        '''<returns>an int representing the number of rows affected by the command</returns>
        Public Shared Function ExecuteNonQuery(ByVal connectionString As StringByVal cmdType As CommandType, ByVal cmdText As StringByVal ParamArray commandParameters As SqlParameter()) As Integer

            
Dim cmd As SqlCommand = New SqlCommand

            Using conn 
As SqlConnection = New SqlConnection(connectionString)
                PrepareCommand(cmd, conn, 
Nothing, cmdType, cmdText, commandParameters)
                
Dim val As Integer = cmd.ExecuteNonQuery()
                cmd.Parameters.Clear()
                conn.Dispose()
                
Return val
            
End Using

        
End Function

        
'''<summary>
        '''Execute a SqlCommand (that returns no resultset) against an existing database connection 
        '''using the provided parameters.
        '''</summary>
        '''<remarks>
        '''e.g.:  
        ''' int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        '''</remarks>
        '''<param name="conection">an existing database connection</param>
        '''<param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
        '''<param name="cmdText">the stored procedure name or T-SQL command</param>
        '''<param name="commandParameters">an array of SqlParamters used to execute the command</param>
        '''<returns>an int representing the number of rows affected by the command</returns>
        Public Shared Function ExecuteNonQuery(ByVal conection As SqlConnection, ByVal cmdType As CommandType, ByVal cmdText As StringByVal ParamArray commandParameters As SqlParameter())

            
Dim cmd As SqlCommand = New SqlCommand
            PrepareCommand(cmd, conection, 
Nothing, cmdType, cmdText, commandParameters)
            
Dim val As Integer = cmd.ExecuteNonQuery()
            cmd.Parameters.Clear()
            
Return val

        
End Function

        
'''<summary>
        '''Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 
        '''using the provided parameters.
        '''</summary>
        '''<remarks>
        '''e.g.:  
        ''' int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        '''</remarks>
        '''<param name="trans">an existing sql transaction</param>
        '''<param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
        '''<param name="cmdText">the stored procedure name or T-SQL command</param>
        '''<param name="commandParameters">an array of SqlParamters used to execute the command</param>
        '''<returns>an int representing the number of rows affected by the command</returns>
        Public Shared Function ExecuteNonQuery(ByVal trans As SqlTransaction, ByVal cmdType As CommandType, ByVal cmdText As StringByVal ParamArray commandParameters As SqlParameter()) As Integer

            
Dim cmd As SqlCommand = New SqlCommand()
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters)
            
Dim val As Integer = cmd.ExecuteNonQuery()
            cmd.Parameters.Clear()
            
Return val

        
End Function

        
'''<summary>
        '''Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        '''using the provided parameters.
        '''</summary>
        '''<remarks>
        '''e.g.:  
        ''' SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        '''</remarks>
        '''<param name="connectionString">a valid connection string for a SqlConnection</param>
        '''<param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
        '''<param name="cmdText">the stored procedure name or T-SQL command</param>
        '''<param name="commandParameters">an array of SqlParamters used to execute the command</param>
        '''<returns>A SqlDataReader containing the results</returns>
        Public Shared Function ExcuteReader(ByVal connectionString As StringByVal cmdType As CommandType, ByVal cmdText As StringByVal ParamArray commandParameters As SqlParameter()) As SqlDataReader
            
Dim cmd As SqlCommand = New SqlCommand()
            
Dim conn As SqlConnection = New SqlConnection(connectionString)

            
Try
                PrepareCommand(cmd, conn, 
Nothing, cmdType, cmdText, commandParameters)
                
Dim rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                cmd.Parameters.Clear()
                
Return rdr
            
Catch ex As Exception
                conn.Close()
                ExceptionManagement.SystemError.SystemLog(ex.Message)
                
Throw
            
End Try

        
End Function

        
'''<summary>
        '''Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        '''using the provided parameters.
        '''</summary>
        '''<remarks>
        '''e.g.:  
        ''' Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        '''</remarks>
        '''<param name="connectionString">a valid connection string for a SqlConnection</param>
        '''<param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
        '''<param name="cmdText">the stored procedure name or T-SQL command</param>
        '''<param name="commandParameters">an array of SqlParamters used to execute the command</param>
        '''<returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        Public Shared Function ExcuteScalar(ByVal connectionString As StringByVal cmdType As CommandType, ByVal cmdText As StringByVal ParamArray commandParameters As SqlParameter()) As Object

            
Dim cmd As SqlCommand = New SqlCommand

            Using connection 
As SqlConnection = New SqlConnection(connectionString)
                
Dim val As Object = cmd.ExecuteScalar
                cmd.Parameters.Clear()
                connection.Dispose()
                
Return val
            
End Using

        
End Function

        
'''<summary>
        ''' Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        '''using the provided parameters.
        '''</summary>
        '''<remarks>
        '''e.g.:  
        ''' Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        '''</remarks>
        '''<param name="connection">an existing database connection</param>
        '''<param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
        '''<param name="cmdText">the stored procedure name or T-SQL command</param>
        '''<param name="commandParameters">an array of SqlParamters used to execute the command</param>
        '''<returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        Public Shared Function ExcuteScalar(ByVal connection As SqlConnection, ByVal cmdType As CommandType, ByVal cmdText As StringByVal ParamArray commandParameters As SqlParameter()) As Object

            
Dim cmd As SqlCommand = New SqlCommand

            PrepareCommand(cmd, connection, 
Nothing, cmdType, cmdText, commandParameters)
            
Dim val As Object = cmd.ExecuteScalar
            cmd.Parameters.Clear()
            connection.Dispose()
            
Return val

        
End Function

        
''' <summary>
        ''' add parameter array to the cache
        ''' </summary>
        ''' <param name="cacheKey">Key to the parameter cache</param>
        ''' <param name="commandParameters">an array of SqlParamters to be cached</param>
        Public Shared Sub CacheParameters(ByVal cacheKey As StringByVal ParamArray commandParameters As SqlParameter())
            parmCache(cacheKey) 
= commandParameters
        
End Sub

        
''' <summary>
        ''' Retrieve cached parameters
        ''' </summary>
        ''' <param name="cacheKey">key used to lookup parameters</param>
        ''' <returns>Cached SqlParamters array</returns>
        Public Shared Function GetCachedParameters(ByVal cacheKey As StringAs SqlParameter()
            
Dim cachedParms() As SqlParameter = CType(parmCache(cacheKey), SqlParameter())
            
If cachedParms Is Nothing Then
                
Return Nothing
            
End If
            
Dim clonedParms As SqlParameter() = New SqlParameter(cachedParms.Length - 1) {}

            
Dim i As Integer
            
For i = 0 To cachedParms.Length - 1
                clonedParms(i) 
= DirectCast(DirectCast(cachedParms(i), ICloneable).Clone(), SqlParameter)
            
Next

            
Return clonedParms

        
End Function

        
'''<summary>
        '''Prepare a command for execution
        '''</summary>
        '''<param name="cmd">SqlCommand object</param>
        '''<param name="conn">SqlConnection object</param>
        '''<param name="trans">SqlTransaction object</param>
        '''<param name="cmdType">Cmd type e.g. stored procedure or text</param>
        '''<param name="cmdText">Command text, e.g. Select * from Products</param>
        '''<param name="cmdParms">SqlParameters to use in the command</param>
        Private Shared Sub PrepareCommand(ByRef cmd As SqlCommand, ByVal conn As SqlConnection, ByVal trans As SqlTransaction, ByVal cmdType As CommandType, ByVal cmdText As StringByVal cmdParms As SqlParameter())
            
If conn.State <> ConnectionState.Open Then
                conn.Open()
            
End If

            cmd.Connection 
= conn
            cmd.CommandText 
= cmdText

            
If trans IsNot Nothing Then
                cmd.Transaction 
= trans
            
End If

            cmd.CommandType 
= cmdType

            
If cmdParms IsNot Nothing Then
                
For Each parm As SqlParameter In cmdParms
                    cmd.Parameters.Add(parm)
                
Next
            
End If

        
End Sub

    
End Class

End Namespace

MSDN

DirectCast 关键字:

引入类型转换操作。该关键字的使用方法与 CType 关键字相同,如下列所示:

Dim Q As Object = 2.37   ' Requires Option Strict to be Off.
Dim I As Integer = CType(Q, Integer)   ' Succeeds.
Dim J As Integer = DirectCast(Q, Integer)   ' Fails.

这两个关键字都将要转换的表达式作为第一个参数,而将要转换成的类型作为第二个参数。如果未定义表达式的数据类型与第二个参数所指定的数据类型之间的转换,那么这两种转换都会失败。

这两个关键字之间的差别在于:只要定义了表达式与类型之间的有效转换,CType 即可成功,而 DirectCast 则要求对象变量的运行时类型与指定的类型相同。不过,如果表达式的指定类型和运行时类型相同,则 DirectCast 的运行时性能比 CType 的运行时性能好。

在上例中,Q 的运行时类型为 DoubleCType 因为 Double 可以转换成 Integer 而成功了,DirectCast 则因为 Q 的运行时类型不是 Integer 而失败了。

如果参数类型不匹配,DirectCast 会引发 InvalidCastException 错误。

Using...End Using :
当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose。
使用using会自动调用引用对象的Dispose方法。可以看成try...catch的缩写。

ConfigurationManager.ConnectionStrings 属性
获取当前应用程序默认配置的 ConnectionStringsSection 数据。
也就是web.config文件中
<connectionStrings>
</connectionStrings>
之间的内容

ConfigurationManager.appSettings属性
获取当前应用程序默认配置的 AppSettingsSection 数据。
 也就是web.config文件中
<AppSettings>
</AppSettings>
之间的内容

System.Collections.Hashtable
是用来表示一组组key/value结构的容器。其结构中Key用来快速查找。


 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Windows API Reference for C#, VB.NET
    不错的.net 下用API的参考站点地址在:http://www.webtropy.com/articles/Win32-API-DllImport-art9.asp 下面摘抄分类,便于大家直接就拿来用: File, Memory, Process, Threading, Time, Console, and Comm control(kernel32.dll) _hread_hwrite_lclose_lcr
    03-16
  • 一个基于API的VB.net串口通讯类 vbnet串口通信
    VB.net的串口通讯支持总是让人觉得有所不足,在使用VB6的MsComm32.ocx时,很多人都会在VB.net的开发中觉得很困扰。    这里讲述的VB.net串口通讯类使用native代码,并且它是通API调用实现的,你会发现VB.net的串口通讯就是这么简单。    在说明如何使
    02-12
  • [VB][ASP.NET]FileUpload控件「批次上传 / 多档
    FileUpload控件「批次上传 / 多档案同时上传」的范例 (VB语法) http://www.dotblogs.com.tw/mis2000lab/archive/2008/05/14/3986.aspx    FileUpload控件真的简单好用,不使用它来作批次上传,却要改用别的方法,实在不聪明。要用就一次用到底,公开File
    02-10
  • 第八章 VB中ActiveX控件的使用
    轉自:http://wwww.hyit.edu.cn/edu/vb/study/index.htm第八章          VB中ActiveX控件的使用8.1  概述     这里的ActiveX控件是指VB标准工具箱里没有的控件,用时需从“工程”菜单里选择“部件…”(或右键单击工具箱,从快捷菜单中选择“部
    02-10
  • 第二章 VB的界面设计
    轉自:http://wwww.hyit.edu.cn/edu/vb/study/index.htm第二章         VB的界面设计2.1  VB用户界面设计基础1. 概述   界面的设计有两步:先绘制控件,然后确定控件属性。   绘制控件:在工具箱里单击想画的控件,在窗体里按下鼠标并拖曳,然后
    02-10
  • C#/VB.NET 获取Excel中图片所在的行、列坐标位置
    C#/VB.NET 获取Excel中图片所在的行、列坐标位
    本文以C#和vb.net代码示例展示如何来获取Excel工作表中图片的坐标位置。这里的坐标位置是指图片左上角顶点所在的单元格行和列位置,横坐标即顶点所在的第几列、纵坐标即顶点所在的第几行。下面是获取图片位置的详细方法及步骤。【程序环境】按照如下方法来引
    02-09
  • VB操作XML
    VB操作XML
    XSL(可扩展样式表语言)是对CSS的一种扩展,功能比CSS强大得多。XML链接是在HTML链接的功能之上加以扩展,可以支持更为复杂的链接,通过XML链接,不仅可以在XML文件之间建立链接,还可以建立其他类型数据之间的链接,其规范分为三个部分:XLink语言,XPointe
    02-09
  • VB6多线程,关键段操作 vb6.0 多线程
    Option Explicit Declare Function GetLastError Lib "kernel32" () As Long 'Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long 'Declare Sub ExitThread Lib "kernel32" (Optional ByVal dwExitCode
    02-09
  • VB.NET调用IE,并且等待
                Dim p As New Process            '获得URL            aURL = GetURL()            '获得IE路径            p.StartInfo.FileName = System.Environment.GetFolderPath( _ 
    02-09
  • vb的VSFlexGrid控件 vb msflexgrid
    多行选中VSFlexGrid的SelectionMode = flexSelectionListBox,现在可以配合Ctrl进行多行选择循环取值用vsflexgrid.SelectedRows 可以得到你选择的行的总数量然后用循环可以得到具体的行中具体列的内容Dim Temp  As StringDim i As IntegerFor i =
    02-09
点击排行