如何从 Perl 中的 MySQL 获取最后一个错误

How to get the last error from MySQL in Perl

我在 Perl 中使用 DBI 来访问 MySQL。

return DBI->connect('DBI:mysql:MyBase:localhost', 'user', 'pass');
…
my $query = $connection->prepare($command);
my $result = $query->execute();
$query->finish;

我希望可以不使用die或者试试。我只希望能够执行 MySQL 命令,然后在下一次调用时检查错误类型。

这可能吗?

根据 connect 的记录:

"If the connect fails (see below), it returns undef and sets both $DBI::err and $DBI::errstr. (It does not explicitly set $!.) You should generally test the return status of connect and print $DBI::errstr if it has failed."

一旦你有了一个句柄,err method must be checked after each database or statement handle method call, and errstr 类似地代表了发生错误时的错误信息。

强烈推荐,DBIx::Connector or Mojo::Pg, to set RaiseError 等包装器确实需要这样做,这样您就可以避免代码混乱和忘记检查错误的可能性。