Sou*_*ers 4 vb.net sqlconnection
找不到确切的问题/答案。在VB.NET中,如果我在Try / Catch块中打开SqlConnection,并且抛出了异常(正确捕获),该连接是否隐式关闭,还是必须将其关闭?(如果尝试失败,它甚至会打开吗?)
我自己会“测试”,但是当抛出异常时,我真的不知道如何判断连接是打开还是关闭。
谢谢!
不。这就是为什么要在try / catch之前声明连接变量,并在其中添加finally,以确保可以放置和关闭连接的原因:
Dim con As New SqlClientConnection( . . .)
Try
' DB Operations (create, read, update, delete) here
con.open()
Catch SqlClientException (ex)
' Deal with exception
Finally
' Code here will always run, whether or not the try code succeeded
' or if you wound up in a catch block. You can safely call .close()
' or (as shown below) .dispose() because if the connection is already
' closed/disposed, the call doesn't do anything.
' Dispose is what you want - it will not only close the
' connection, but it will release the .NET reference to
' the remote resource, freeing up that resource (the database
' in this case) to serve other clients.
con.Dispose()
End Try
Run Code Online (Sandbox Code Playgroud)