SQLHelper.vb是2004年微软发布的一个使用ADO.Net方法对SQL Server数据库进行操作的封装类。在网上贴出的SqlHelper类大多是C#版本,如果需要VB.NET版本的微软官方原版SqlHelper类,可以进行如下操作获取。
一、获取SQLHelper.vb
需要从微软官方下载Data Access Application Block for .NET v2,下载地址:https://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=435 。如图:
下载下来是一个.msi安装程序,直接安装就可以,然后在安装文件夹(C:\Program Files\Microsoft Application Blocks for .NET\Data Access v2\Code\VB\Microsoft.ApplicationBlocks.Data)里找到SQLHelper.vb文件,用记事本打开文件即可看到代码。
二、SQLHelper帮助类代码
SQLHelper.vb代码如下:
' The SqlHelper class is intended to encapsulate high performance, scalable best practices for
' common uses of SqlClient.
' ===============================================================================
' Release history
' VERSION DESCRIPTION
' 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods
'
' ===============================================================================
Public NotInheritable Class SqlHelper
#Region "private utility methods & constructors"
' Since this class provides only static methods, make the default constructor private to prevent
' instances from being created with "new SqlHelper()".
Private Sub New()
End Sub ' New
' This method is used to attach array of SqlParameters to a SqlCommand.
' This method will assign a value of DbNull to any parameter with a direction of
' InputOutput and a value of null.
' This behavior will prevent default values from being used, but
' this will be the less common case than an intended pure output parameter (derived as InputOutput)
' where the user provided no input value.
' Parameters:
' -command - The command to which the parameters will be added
' -commandParameters - an array of SqlParameters to be added to command
Private Shared Sub AttachParameters(ByVal command As SqlCommand, ByVal commandParameters() As SqlParameter)
If (command Is Nothing) Then Throw New ArgumentNullException("command")
If (Not commandParameters Is Nothing) Then
Dim p As SqlParameter
For Each p In commandParameters
If (Not p Is Nothing) Then
' Check for derived output value with no value assigned
If (p.Direction = ParameterDirection.InputOutput OrElse p.Direction = ParameterDirection.Input) AndAlso p.Value Is Nothing Then
p.Value = DBNull.Value
End If
command.Parameters.Add(p)
End If
Next p
End If
End Sub ' AttachParameters
' This method assigns dataRow column values to an array of SqlParameters.
' Parameters:
' -commandParameters: Array of SqlParameters to be assigned values
' -dataRow: the dataRow used to hold the stored procedure' s parameter values
Private Overloads Shared Sub AssignParameterValues(ByVal commandParameters() As SqlParameter, ByVal dataRow As DataRow)
If commandParameters Is Nothing OrElse dataRow Is Nothing Then
' Do nothing if we get no data
Exit Sub
End If
' Set the parameters values
Dim commandParameter As SqlParameter
Dim i As Integer
For Each commandParameter In commandParameters
' Check the parameter name
If (commandParameter.ParameterName Is Nothing OrElse commandParameter.ParameterName.Length <= 1) Then
Throw New Exception(String.Format("Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: ' {1}' .", i, commandParameter.ParameterName))
End If
If dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) <> -1 Then
commandParameter.Value = dataRow(commandParameter.ParameterName.Substring(1))
End If
i = i + 1
Next
End Sub
' This method assigns an array of values to an array of SqlParameters.
' Parameters:
' -commandParameters - array of SqlParameters to be assigned values
' -array of objects holding the values to be assigned
Private Overloads Shared Sub AssignParameterValues(ByVal commandParameters() As SqlParameter, ByVal parameterValues() As Object)
Dim i As Integer
Dim j As Integer
If (commandParameters Is Nothing) AndAlso (parameterValues Is Nothing) Then
' Do nothing if we get no data
Return
End If
' We must have the same number of values as we pave parameters to put them in
If commandParameters.Length <> parameterValues.Length Then
Throw New ArgumentException("Parameter count does not match Parameter Value count.")
End If
' Value array
j = commandParameters.Length - 1
For i = 0 To j
' If the current array value derives from IDbDataParameter, then assign its Value property
If TypeOf parameterValues(i) Is IDbDataParameter Then
Dim paramInstance As IDbDataParameter = CType(parameterValues(i), IDbDataParameter)
If (paramInstance.Value Is Nothing) Then
commandParameters(i).Value = DBNull.Value
Else
commandParameters(i).Value = paramInstance.Value
End If
ElseIf (parameterValues(i) Is Nothing) Then
commandParameters(i).Value = DBNull.Value
Else
commandParameters(i).Value = parameterValues(i)
End If
Next
End Sub ' AssignParameterValues
' This method opens (if necessary) and assigns a connection, transaction, command type and parameters
' to the provided command.
' Parameters:
' -command - the SqlCommand to be prepared
' -connection - a valid SqlConnection, on which to execute this command
' -transaction - a valid SqlTransaction, or ' null'
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' -commandParameters - an array of SqlParameters to be associated with the command or ' null' if no parameters are required
Private Shared Sub PrepareCommand(ByVal command As SqlCommand, _
ByVal connection As SqlConnection, _
ByVal transaction As SqlTransaction, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal commandParameters() As SqlParameter, ByRef mustCloseConnection As Boolean)
If (command Is Nothing) Then Throw New ArgumentNullException("command")
If (commandText Is Nothing OrElse commandText.Length = 0) Then Throw New ArgumentNullException("commandText")
' If the provided connection is not open, we will open it
If connection.State <> ConnectionState.Open Then
connection.Open()
mustCloseConnection = True
Else
mustCloseConnection = False
End If
' Associate the connection with the command
command.Connection = connection
' Set the command text (stored procedure name or SQL statement)
command.CommandText = commandText
' If we were provided a transaction, assign it.
If Not (transaction Is Nothing) Then
If transaction.Connection Is Nothing Then Throw New ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction")
command.Transaction = transaction
End If
' Set the command type
command.CommandType = commandType
' Attach the command parameters if they are provided
If Not (commandParameters Is Nothing) Then
AttachParameters(command, commandParameters)
End If
Return
End Sub ' PrepareCommand
#End Region
#Region "ExecuteNonQuery"
' Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
' the connection string.
' e.g.:
' Dim result As Integer = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders")
' Parameters:
' -connectionString - a valid connection string for a SqlConnection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal connectionString As String, _
ByVal commandType As CommandType, _
ByVal commandText As String) As Integer
' Pass through the call providing null for the set of SqlParameters
Return ExecuteNonQuery(connectionString, commandType, commandText, CType(Nothing, SqlParameter()))
End Function ' ExecuteNonQuery
' Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
' using the provided parameters.
' e.g.:
' Dim result As Integer = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24))
' Parameters:
' -connectionString - a valid connection string for a SqlConnection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' -commandParameters - an array of SqlParamters used to execute the command
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal connectionString As String, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal ParamArray commandParameters() As SqlParameter) As Integer
If (connectionString Is Nothing OrElse connectionString.Length = 0) Then Throw New ArgumentNullException("connectionString")
' Create & open a SqlConnection, and dispose of it after we are done
Dim connection As SqlConnection
Try
connection = New SqlConnection(connectionString)
connection.Open()
' Call the overload that takes a connection in place of the connection string
Return ExecuteNonQuery(connection, commandType, commandText, commandParameters)
Finally
If Not connection Is Nothing Then connection.Dispose()
End Try
End Function ' ExecuteNonQuery
' Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
' the connection string using the provided parameter values. This method will discover the parameters for the
' stored procedure, and assign the values based on parameter order.
' This method provides no access to output parameters or the stored procedure' s return value parameter.
' e.g.:
' Dim result As Integer = ExecuteNonQuery(connString, "PublishOrders", 24, 36)
' Parameters:
' -connectionString - a valid connection string for a SqlConnection
' -spName - the name of the stored procedure
' -parameterValues - an array of objects to be assigned as the input values of the stored procedure
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal connectionString As String, _
ByVal spName As String, _
ByVal ParamArray parameterValues() As Object) As Integer
If (connectionString Is Nothing OrElse connectionString.Length = 0) Then Throw New ArgumentNullException("connectionString")
If (spName Is Nothing OrElse spName.Length = 0) Then Throw New ArgumentNullException("spName")
Dim commandParameters As SqlParameter()
' If we receive parameter values, we need to figure out where they go
If Not (parameterValues Is Nothing) AndAlso parameterValues.Length > 0 Then
' Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName)
' Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues)
' Call the overload that takes an array of SqlParameters
Return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters)
' Otherwise we can just call the SP without params
Else
Return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName)
End If
End Function ' ExecuteNonQuery
' Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
' e.g.:
' Dim result As Integer = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders")
' Parameters:
' -connection - a valid SqlConnection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal connection As SqlConnection, _
ByVal commandType As CommandType, _
ByVal commandText As String) As Integer
' Pass through the call providing null for the set of SqlParameters
Return ExecuteNonQuery(connection, commandType, commandText, CType(Nothing, SqlParameter()))
End Function ' ExecuteNonQuery
' Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
' using the provided parameters.
' e.g.:
' Dim result As Integer = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24))
' Parameters:
' -connection - a valid SqlConnection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' -commandParameters - an array of SqlParamters used to execute the command
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal connection As SqlConnection, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal ParamArray commandParameters() As SqlParameter) As Integer
If (connection Is Nothing) Then Throw New ArgumentNullException("connection")
' Create a command and prepare it for execution
Dim cmd As New SqlCommand
Dim retval As Integer
Dim mustCloseConnection As Boolean = False
PrepareCommand(cmd, connection, CType(Nothing, SqlTransaction), commandType, commandText, commandParameters, mustCloseConnection)
' Finally, execute the command
retval = cmd.ExecuteNonQuery()
' Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear()
If (mustCloseConnection) Then connection.Close()
Return retval
End Function ' ExecuteNonQuery
' Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
' using the provided parameter values. This method will discover the parameters for the
' stored procedure, and assign the values based on parameter order.
' This method provides no access to output parameters or the stored procedure' s return value parameter.
' e.g.:
' Dim result As integer = ExecuteNonQuery(conn, "PublishOrders", 24, 36)
' Parameters:
' -connection - a valid SqlConnection
' -spName - the name of the stored procedure
' -parameterValues - an array of objects to be assigned as the input values of the stored procedure
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal connection As SqlConnection, _
ByVal spName As String, _
ByVal ParamArray parameterValues() As Object) As Integer
If (connection Is Nothing) Then Throw New ArgumentNullException("connection")
If (spName Is Nothing OrElse spName.Length = 0) Then Throw New ArgumentNullException("spName")
Dim commandParameters As SqlParameter()
' If we receive parameter values, we need to figure out where they go
If Not (parameterValues Is Nothing) AndAlso parameterValues.Length > 0 Then
' Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName)
' Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues)
' Call the overload that takes an array of SqlParameters
Return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters)
Else ' Otherwise we can just call the SP without params
Return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName)
End If
End Function ' ExecuteNonQuery
' Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
' e.g.:
' Dim result As Integer = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders")
' Parameters:
' -transaction - a valid SqlTransaction associated with the connection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal transaction As SqlTransaction, _
ByVal commandType As CommandType, _
ByVal commandText As String) As Integer
' Pass through the call providing null for the set of SqlParameters
Return ExecuteNonQuery(transaction, commandType, commandText, CType(Nothing, SqlParameter()))
End Function ' ExecuteNonQuery
' Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
' using the provided parameters.
' e.g.:
' Dim result As Integer = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24))
' Parameters:
' -transaction - a valid SqlTransaction
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' -commandParameters - an array of SqlParamters used to execute the command
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal transaction As SqlTransaction, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal ParamArray commandParameters() As SqlParameter) As Integer
If (transaction Is Nothing) Then Throw New ArgumentNullException("transaction")
If Not (transaction Is Nothing) AndAlso (transaction.Connection Is Nothing) Then Throw New ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction")
' Create a command and prepare it for execution
Dim cmd As New SqlCommand
Dim retval As Integer
Dim mustCloseConnection As Boolean = False
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, mustCloseConnection)
' Finally, execute the command
retval = cmd.ExecuteNonQuery()
' Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear()
Return retval
End Function ' ExecuteNonQuery
' Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlTransaction
' using the provided parameter values. This method will discover the parameters for the
' stored procedure, and assign the values based on parameter order.
' This method provides no access to output parameters or the stored procedure' s return value parameter.
' e.g.:
' Dim result As Integer = SqlHelper.ExecuteNonQuery(trans, "PublishOrders", 24, 36)
' Parameters:
' -transaction - a valid SqlTransaction
' -spName - the name of the stored procedure
' -parameterValues - an array of objects to be assigned as the input values of the stored procedure
' Returns: An int representing the number of rows affected by the command
Public Overloads Shared Function ExecuteNonQuery(ByVal transaction As SqlTransaction, _
ByVal spName As String, _
ByVal ParamArray parameterValues() As Object) As Integer
If (transaction Is Nothing) Then Throw New ArgumentNullException("transaction")
If Not (transaction Is Nothing) AndAlso (transaction.Connection Is Nothing) Then Throw New ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction")
If (spName Is Nothing OrElse spName.Length = 0) Then Throw New ArgumentNullException("spName")
Dim commandParameters As SqlParameter()
' If we receive parameter values, we need to figure out where they go
If Not (parameterValues Is Nothing) AndAlso parameterValues.Length > 0 Then
' Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName)
' Assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues)
' Call the overload that takes an array of SqlParameters
Return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters)
Else ' Otherwise we can just call the SP without params
Return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName)
End If
End Function ' ExecuteNonQuery
#End Region
#Region "ExecuteDataset"
' Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
' the connection string.
' e.g.:
' Dim ds As DataSet = SqlHelper.ExecuteDataset("", commandType.StoredProcedure, "GetOrders")
' Parameters:
' -connectionString - a valid connection string for a SqlConnection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' Returns: A dataset containing the resultset generated by the command
Public Overloads Shared Function ExecuteDataset(ByVal connectionString As String, _
ByVal commandType As CommandType, _
ByVal commandText As String) As DataSet
' Pass through the call providing null for the set of SqlParameters
Return ExecuteDataset(connectionString, commandType, commandText, CType(Nothing, SqlParameter()))
End Function ' ExecuteDataset
' Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
' using the provided parameters.
' e.g.:
' Dim ds As Dataset = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24))
' Parameters:
' -connectionString - a valid connection string for a SqlConnection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' -commandParameters - an array of SqlParamters used to execute the command
' Returns: A dataset containing the resultset generated by the command
Public Overloads Shared Function ExecuteDataset(ByVal connectionString As String, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal ParamArray commandParameters() As SqlParameter) As DataSet
If (connectionString Is Nothing OrElse connectionString.Length = 0) Then Throw New ArgumentNullException("connectionString")
' Create & open a SqlConnection, and dispose of it after we are done
Dim connection As SqlConnection
Try
connection = New SqlConnection(connectionString)
connection.Open()
' Call the overload that takes a connection in place of the connection string
Return ExecuteDataset(connection, commandType, commandText, commandParameters)
Finally
If Not connection Is Nothing Then connection.Dispose()
End Try
End Function ' ExecuteDataset
' Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
' the connection string using the provided parameter values. This method will discover the parameters for the
' stored procedure, and assign the values based on parameter order.
' This method provides no access to output parameters or the stored procedure' s return value parameter.
' e.g.:
' Dim ds As Dataset= ExecuteDataset(connString, "GetOrders", 24, 36)
' Parameters:
' -connectionString - a valid connection string for a SqlConnection
' -spName - the name of the stored procedure
' -parameterValues - an array of objects to be assigned as the input values of the stored procedure
' Returns: A dataset containing the resultset generated by the command
Public Overloads Shared Function ExecuteDataset(ByVal connectionString As String, _
ByVal spName As String, _
ByVal ParamArray parameterValues() As Object) As DataSet
If (connectionString Is Nothing OrElse connectionString.Length = 0) Then Throw New ArgumentNullException("connectionString")
If (spName Is Nothing OrElse spName.Length = 0) Then Throw New ArgumentNullException("spName")
Dim commandParameters As SqlParameter()
' If we receive parameter values, we need to figure out where they go
If Not (parameterValues Is Nothing) AndAlso parameterValues.Length > 0 Then
' Pull the parameters for this st