zoukankan      html  css  js  c++  java
  • 【ASP.Net】Pet Shop4.0学习笔记1(VB)

    最近在学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用来快速查找。



  • 相关阅读:
    「mysql优化专题」90%程序员面试都用得上的索引优化手册(5)
    「mysql优化专题」你们要的多表查询优化来啦!请查收(4)
    「mysql优化专题」单表查询优化的一些小总结,非索引设计(3)
    mysql优化专题」90%程序员都会忽略的增删改优化(2)
    「mysql优化专题」这大概是一篇最好的mysql优化入门文章(1)
    zookeeper
    linux查看进程是否存在,不存在则重启
    mysql导出文本文件,加分隔符
    oracle查看表空间和物理文件大小
    oracle插入
  • 原文地址:https://www.cnblogs.com/sekihin/p/811544.html
  • Copyright © 2011-2022 走看看
    Creative Commons License 本作品采用 知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。