[英]VB.NET Using in Using
我可不可以做:
using connection
myDt1 = sqlSelect(connection, sql)
myDt2 = sqlSelect(connection, sql)
end using
與SQLSelect:
Public Shared Function SQLSelect(ByVal provider As SqlConnection, ByVal strSQL As String, ByVal ParamArray params() As SqlParameter) As DataTable
Using connection = provider
SQLSelect = New DataTable
Dim dtReader As SqlDataReader
Dim command As SqlCommand = CreateSQLCommand(provider, strSQL, params)
Try
connection.Open()
dtReader = command.ExecuteReader()
SQLSelect.Load(dtReader)
dtReader.Close()
Catch ex As Exception
SQLSelect = Nothing
Finally
'If connection.State = ConnectionState.Open Then
' connection.Close()
'End If
command.Dispose()
End Try
End Using '<--- Here drop connection
Return SQLSelect
因為在SQLSelect函數中,在使用結束時,連接斷開了! 因此,當我嘗試連接到第二個查詢時出現錯誤。
謝謝
只需使用如下DAL模式:
Public Class DataAccessLayer
'Implements IDataAccessLayer
#Region "Members"
Private ReadOnly connectionString As String
Private ReadOnly configuration As IConfiguration
Private ReadOnly exceptionHandler As IExceptionHandler
#End Region
#Region "Constructors"
Public Sub New()
Me.New(New Configuration(), New ExceptionHandler())
End Sub
Public Sub New(configuration As IConfiguration, exceptionHandler As IExceptionHandler)
' You can just pass in a ConnectionString, instead of my IConfiguration
connectionString = configuration.GetDefaultConnectionString()
'Me.exceptionHandler = exceptionHandler
End Sub
#End Region
#Region "Opening and Closing Connection"
Public Function GetConnection() As SqlConnection
Dim conn = New SqlConnection(connectionString)
Try
conn.Open()
Catch ex As SqlException
'exceptionHandler.LogExceptions(ex, Nothing)
Catch ex As Exception
'exceptionHandler.LogExceptions(ex, Nothing)
End Try
Return conn
End Function
#End Region
#Region "Stored Procedure Calls"
Public Function TestConnection() As Boolean
Try
Dim conn = New SqlConnection(connectionString)
conn.Open()
conn.Close()
Catch
Return False
End Try
Return True
End Function
Public Function CallAStoredProcExample() As Boolean
Dim codeObject As CodeObject = Nothing
Try
Using conn = Me.GetConnection()
Using sqlCommand = New SqlCommand("sp_GetCodeByCodeID", conn)
sqlCommand.CommandType = CommandType.StoredProcedure
sqlCommand.Parameters.AddWithValue("@CodeId", 1)
Using dr = sqlCommand.ExecuteReader()
While dr.Read()
codeObject = New CodeObject(dr, True)
End While
End Using
End Using
End Using
Catch ex As Exception
Return False
End Try
Return True
End Function
End Class
...
調用代碼:
Dim DAL = New DataAccessLayer(yourConnectionString, Nothing)
DAL.CallAStoredProcExample()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.