如何确定 Perl DBI 数据库处理程序的连接状态
如何确定 Perl DBI 数据库处理程序的连接状态(连接是否打开)?类似于.NET SqlConnection.State == Open。可能类似于
defined($dbh->do("some nop sql"))
但找不到要使用的 sql nop 语句。
How to determine connection state of Perl DBI database handler(is connection opend)? Something like .NET SqlConnection.State == Open. May be something like
defined($dbh->do("some nop sql"))
but can't find sql nop statement to use.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来询问数据库句柄是否已连接
您可以通过调用某些数据库驱动程序不实现
ping
但 DBD::mysql 。另一种方法是运行一个空选择,例如 MySQL 的select 1
。我假设 MySQL 因为这就是你的问题的标记方式。其他数据库的答案会略有不同。You can ask you database handle if it is connected by calling
Some DB Drivers don't implement
ping
but DBD::mysql does. An alternative is to run an empty select likeselect 1
for MySQL. I'm assuming MySQL since that is how your question is tagged. Other databases will have slightly different answers.这个答案有两个部分。
第一个答案是
{Active}
字段。 perldoc DBI 说:这可能就是您想要检查的内容。
第二个答案是,虽然您可以调用
ping()
,或检查SELECT 1
的结果,但没有多大意义。这确实会告诉您在检查时数据库句柄是否已连接。但您真正想知道的是,当您执行下一步操作时,数据库句柄是否已连接,对吧?而且您的支票和您实际想要做的任何事情之间的连接总是有可能失败。因此,其中任何一个的真实结果并不能保证任何事情。如果您正在进行状态监控,那么
ping()
或SELECT 1
就可以了。但是,在应用程序中,在执行某些操作之前不要检查 dbh 的有效性。只需连接,并使用您返回的 dbh,并在每一步进行适当的错误检查。正确检查错误是无可替代的。There are two parts to this answer.
The first answer is the
{Active}
field.perldoc DBI
says:That's probably what you want to check.
The second answer is that, while you can call
ping()
, or check the result ofSELECT 1
, there's not much point. That will indeed tell you if the database handle is connected at the time of that check. But what you really want to know is whether the database handle is connected when you do what you're about to do next, right? And there's always a chance that the connection will fail between your check and whatever it is you actually want to do. So a true result from either of those isn't a guarantee of anything.If you're doing status monitoring, then a
ping()
orSELECT 1
will do fine. In an application, though, don't check a dbh's validity before doing something. Just connect, and use the dbh you get back, and do proper error-checking at every step. There's no substitute for correctly checking for errors.ping 方法 - 尽管它的作用取决于数据库驱动程序。
The ping method - though what it does is going to be database driver dependent.
还有
$dbh->state()
但每次调用时进行正确的错误检查更加确定。
there's also
$dbh->state()
but yeah proper error-checking at every call is more certain.