为什么我使用 Perl 的 DBI->connect 会默默失败?
为什么这段代码会默默地失败?我怎样才能让它准确地显示 SQL 错误是什么?
$dbh=DBI->connect($db_name,$db_user,$db_pass);
我将代码修改为如下所示:
$dbh=DBI->connect($db_name,$db_user,$db_pass)
or die("could not connect to db: $db_name");
它不会允许我使用未分配的 $dbh
,而是会按预期失败,但它并没有告诉我失败的确切原因。据我所知, $db_name
等的值都设置为有效值。
我知道真正的错误(MySQL 服务器实际上没有运行),但为了将来的参考,我想看到真正的错误,以防我导致身份验证失败。
Why does this code fail silently? How do I get it to show me exactly what the SQL error is?
$dbh=DBI->connect($db_name,$db_user,$db_pass);
I modified the code to look like this:
$dbh=DBI->connect($db_name,$db_user,$db_pass)
or die("could not connect to db: $db_name");
Which instead of allowing me to use $dbh
unassigned, it will fail as expected, but it does not tell me exactly why it's failing. The values of $db_name
etc, are all set with valid values as far as I can see.
I know the real error (the MySQL server is actually not running) but for future reference, I'd like to see the true error in case I am causing an auth failure for example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您不明白为什么
connect
失败,因为您没有执行 DBI 的操作 告诉你如何做。错误将出现在$DBI::errstr
变量中:确保您阅读了要使用的任何函数或方法的文档。 :)
You're not seeing why the
connect
fails because you aren't doing what the DBI show you to do. The error will be in the$DBI::errstr
variable:Ensure you read the documentation for any functions or methods that you want to use. :)
啊哈,错误存储在
$DBI::errstr
中,因此我可以像这样修改我的代码:根据文档,它在设计上会默默地失败。
Aha, the error is stored in
$DBI::errstr
, so I can modify my code like so:According to the documentation, it fails silently by design.
通过 RaiseError => 1 作为连接时的选项,那么您的脚本将因错误而终止。我的 Perl 商店有一个标准配置:
Pass RaiseError => 1 as an option when connecting, then your script will die on errors. My Perl shop has a standard configuration of:
这是我对 rjh 的答案。我想我比
die
方法更喜欢这种方法,但还不确定......Here's my usage of rjh's answer. I think I prefer this over the
die
approach, but not sure yet...您使用“或”是语法错误。列出的代码根本不应该运行。
您需要:
请注意,
or die...
是原始语句的一部分,而不是新语句。Your use of 'or' is a syntax error. The listed code should not run at all.
You want:
Note that
or die...
is part of the original statement, not a new statement.尝试包含 $ 的值!在你的死亡消息中。
请参阅$!在 perldoc perlvar 中。
Try including the value of $! in your die message.
See $! in perldoc perlvar.