如何在perl中检查先前执行的命令的状态
How to check status of previously executed command in perl
我对 Perl 完全陌生。我有一个 Perl 脚本,它检查容器中与 oracle 数据库 运行 的连接。这是我的代码
#!/usr/bin/perl
use DBI;
$\="\n";
print "Connecting to DB..";
my $dbh = DBI->connect('dbi:Oracle:host=oracle;sid=ORCLCDB;port=1521', 'books_admin/MyPassword', '',{ RaiseError => 1, AutoCommit => 0 })or die print ("could not connect! $DBI::errstr \n");
使用这个脚本我可以连接到 oracle 数据库。但是这个脚本没有给我的终端提供任何状态输出。我如何检查脚本是否已连接到数据库?。我知道 bash 有 $?用于检查先前执行的 cmd 的状态。我们在 Perl 中有类似的东西吗?
这就是我想要的
当连接正常时输出 "Successfully connected to Oracle-db",当脚本无法连接到数据库时输出失败状态
注意:此代码为我的终端提供了错误状态。
我的 Perl 版本是 v5.16.3
documentation for the connect()
method 是这样说的:
Establishes a database connection, or session, to the requested $data_source
. Returns a database handle object if the connection succeeds. Use $dbh->disconnect
to terminate the connection.
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.
因此您的代码可以像这样显而易见:
my $dbh = DBI->connect(...);
if ($dbh) {
say 'Connection ok';
} else {
die "Connection error: $DBI::errstr";
}
但是,您正在使用 RaiseError => 1
,因此您的程序将 die
而不是返回 undef
。因此,如果您的程序通过了那条线,您就知道连接成功了。
my $dbh = DBI->connect(...);
say 'Connection ok';
我对 Perl 完全陌生。我有一个 Perl 脚本,它检查容器中与 oracle 数据库 运行 的连接。这是我的代码
#!/usr/bin/perl
use DBI;
$\="\n";
print "Connecting to DB..";
my $dbh = DBI->connect('dbi:Oracle:host=oracle;sid=ORCLCDB;port=1521', 'books_admin/MyPassword', '',{ RaiseError => 1, AutoCommit => 0 })or die print ("could not connect! $DBI::errstr \n");
使用这个脚本我可以连接到 oracle 数据库。但是这个脚本没有给我的终端提供任何状态输出。我如何检查脚本是否已连接到数据库?。我知道 bash 有 $?用于检查先前执行的 cmd 的状态。我们在 Perl 中有类似的东西吗?
这就是我想要的 当连接正常时输出 "Successfully connected to Oracle-db",当脚本无法连接到数据库时输出失败状态
注意:此代码为我的终端提供了错误状态。 我的 Perl 版本是 v5.16.3
documentation for the connect()
method 是这样说的:
Establishes a database connection, or session, to the requested
$data_source
. Returns a database handle object if the connection succeeds. Use$dbh->disconnect
to terminate the connection.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 ofconnect
and print$DBI::errstr
if it has failed.
因此您的代码可以像这样显而易见:
my $dbh = DBI->connect(...);
if ($dbh) {
say 'Connection ok';
} else {
die "Connection error: $DBI::errstr";
}
但是,您正在使用 RaiseError => 1
,因此您的程序将 die
而不是返回 undef
。因此,如果您的程序通过了那条线,您就知道连接成功了。
my $dbh = DBI->connect(...);
say 'Connection ok';