如何检测 TadoConnection 丢失了与服务器的通信?

问题描述:

我需要检测 TAdoConnection 组件已失去与服务器的连接.我试过使用 OnDisconnect事件,但这仅在调用 Close 方法或 Connected 属性设置为 false 时触发.

I need to detect when a TAdoConnection component has lost the connection with the server. I've tried using the OnDisconnect event but this only fires when the Close method is called or the Connected property is set to false.

我尝试过的另一个选项是使用 TTimer 并执行查询像这样

Another option I've tried is using a TTimer and executing a query like this

SELECT 1 RESULT FROM DUAL

在 OnTimer 事件中,捕获发生的任何异常.

in the OnTimer event, catching any exception that occurs.

是否有更好的方法来检测连接丢失?

Is there a better option to detect that the connection was lost?

我看到了 DUAL 表.意思是,你正在使用 Oracle :)

I see the DUAL table. Means, you are using the Oracle :)

对于大多数(所有?)客户端/服务器 DBMS,除了要求 DBMS 执行某些操作之外,无法检测到连接丢失.连接丢失的原因有很多.可能是网络故障,可能是……,可能是 DBA 关闭了 DB.

For most (all ?) client / server DBMS's there is no way to detect, that a connection is losted, other than to ask a DBMS for some action. And there are a lot of reasons, why a connection is losted. May be a network failure, may be ..., may be a DBA shutdowned a DB.

许多 DBMS API,包括 Oracle OCI,都具有特殊功能,允许 ping DBMS.ping"是对 DBMS 的最小可能请求.上面的 SELECT 需要更多的工作,而不是这样的 ping.

Many DBMS API's, including Oracle OCI, have the special functions, allowing to ping a DBMS. The "ping" is a smallest possible request to a DBMS. The above SELECT requires much more job, than such ping.

但并非所有数据访问组件(包括 ADO)都允许使用 DBMS API ping 调用 ping 一个 DBMS.然后你必须使用一些 SQL 命令.所以,上面的 SELECT 对 ADO 是正确的.其他选项 - BEGIN NULL;结尾;.它可能使用较少的 DBMS 资源(不需要优化器,不需要描述结果集等).

But not all data access components, including ADO, allows to ping a DBMS, using the DBMS API ping call. Then you have to use some SQL command. So, the above SELECT is correct with ADO. Other option - BEGIN NULL; END;. It may be using less DBMS resources (no need for optimizer, no need to describe a result set, etc).

TTimer 没问题.查询应该在一个线程中执行,在该线程中使用相应的连接.虽然不是必须的,但这是一个不同的问题.

TTimer is OK. The query should be performed in a thread, where the corresponding connection is used. Not a must although, but it is a different issue.

潜在的问题可能是在连接丢失时关闭连接.由于 DBMS API 可能处于失败状态,因此连接关闭可能会引发异常.

The potential problem may be to close a connection, when a connection is losted. As a connection closing may raise an exception due to the DBMS API may be in a failed state.

那种……