【问题标题】:Is it possible to stop MSSQL Connection?是否可以停止 MSSQL 连接?
【发布时间】:2022-12-06 18:20:28
【问题描述】:

我目前正在开发一个将连接到 SQL 服务器的应用程序。第一次尝试打开连接失败后或发送 Connection.Open() 15 秒后是否可以停止或中止连接?

示例代码如下:

     Dim conn As New SqlClient.SqlConnection
     conn.ConnectionString = connstr
         Try
            conn.Open()
'Drop or abort the connection after 15 seconds or after failing the first attempt to connect
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

【问题讨论】:

  • 您可以在 Catch 块中处理请求的代码。此外,还有一个 finally 块在成功或失败状态后执行。
  • ConnectionTimeout 属性默认为 30(秒)。如果需要,您可以将其更改为 15。如果在没有成功连接的情况下该时间段到期,将抛出一个特定的SqlException
  • 实际上,我必须在那里纠正自己。其实是SqlCommand.CommandTimeout属性默认为30。SqlConnection.ConnectionTimeout属性默认已经是15了。看起来你已经拥有了你想要的,虽然“第一次尝试打开连接失败或 Connection.Open() 发送后 15 秒失败”是两个截然不同的东西。
  • 您好,实际上我已经尝试在我的连接字符串中设置 ConnectionTimeout 属性,但在大约 30 秒到 45 秒后显示错误,有时正好是 15 秒。

标签: sql sql-server vb.net sql-server-2008


【解决方案1】:

是的,可以在一定时间后或连接尝试失败时中止与 SQL 服务器的连接。在您的代码中,您可以在任务中使用 SqlConnection.Open() 方法并使用 Task.Wait() 方法指定超时值。如果连接尝试花费的时间超过指定的超时时间,则 Wait() 方法将抛出一个 TimeoutException,您可以捕获并适当地处理它。

以下是如何在代码中实现此功能的示例:

Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = connstr

Try
   ' Open the connection in a Task with a timeout of 15 seconds
   Dim openTask = Task.Factory.StartNew(Sub() conn.Open())
   openTask.Wait(15000)

' If the connection was not opened within 15 seconds, throw a TimeoutException
If Not openTask.IsCompleted Then
    Throw New TimeoutException("The connection attempt timed out.")
End If
Catch ex As TimeoutException
   ' Handle the timeout exception here
    MsgBox("The connection attempt timed out.")
Catch ex As Exception
' Handle other exceptions here
     MsgBox(ex.Message)
End Try

请注意,如果连接尝试时间超过 15 秒,此方法不会中止连接尝试,但会抛出一个您可以在代码中处理的异常。如果由于任何其他原因而失败,您也可以使用此方法中止连接尝试,方法是在 Try 块中捕获适当的异常。

请务必注意,在一定时间后中止连接尝试或失败可能会导致 SQL 服务器出现问题,应谨慎使用。将您的应用程序设计为优雅地处理连接问题并重试失败的连接尝试,而不是简单地中止它们,通常会更好。

【讨论】:

  • 感谢您提供的信息丰富的回复,我会尝试提供更新。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2012-03-11
  • 2011-11-01
  • 2011-03-05
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多