如何刷新 SqlConnection 的状态?
我有这个代码:
if ( con.SqlConnection.State == System.Data.ConnectionState.Broken ||
con.SqlConnection.State == System.Data.ConnectionState.Closed
){
con.SqlConnection.Open();
}
我失去了与网络的连接。当我来到我的 if
时,我的 SqlConnection.State
仍然显示打开。
如何刷新 SqlConnection
的状态
I have this code:
if ( con.SqlConnection.State == System.Data.ConnectionState.Broken ||
con.SqlConnection.State == System.Data.ConnectionState.Closed
){
con.SqlConnection.Open();
}
I have lost connection to the network. When i come to my if
, then my SqlConnection.State
still says open.
How do i refresh my state of my SqlConnection
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是您应该依赖异常的少数情况之一。
Microsoft 实际上建议您对异常做出反应,而不是检查该状态变量。想象一下这样的情况:您检查变量,然后一纳秒后连接断开。
我相信会抛出的两个是
InvalidOperationException
或SqlException
。This is one of the few cases where you should rely on exceptions.
Microsoft actually recommends that you react to an exception versus check that state variable. Think of the case where you check the variable, and then a nanosecond later the connection goes down.
I believe the two that would get thrown are
InvalidOperationException
orSqlException
.在 TCP 连接上,只有一种有保证的方法可以了解连接是否仍处于活动状态,即向打开的套接字发送新数据包。
因此,只要我们假设您通过 TCP 连接连接到 Sql Server,则该规则也适用。因此,如果出现异常,您需要发送数据并等待。
On TCP connections, there is only one guaranteed way to understand if the connection is still alive or not, it is sending a new packet to the open socket.
So as long as we assume you're connected to Sql Server through a TCP connection, this rule applies to it also. So you need to do send data and wait if an exception is raised.
您始终可以使用 SqlConnection.StateChange 事件
You can always monitor the state of your
SqlConnection
by using the SqlConnection.StateChange Event懒惰的方法:“SELECT 0”。如果命令失败,连接状态将更新为“已关闭”
The lazy way: "SELECT 0". If the command fails, the connection state is updated to "Closed"