gpt4 book ai didi

VB.NET 如果抛出异常,SqlConnection 是否会在 Try/Catch 中自动关闭?

转载 作者:行者123 更新时间:2023-12-05 00:56:37 26 4
gpt4 key购买 nike

没有找到这个确切的问题/答案。在 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

关于VB.NET 如果抛出异常,SqlConnection 是否会在 Try/Catch 中自动关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com