I am completely new to Perl . I have a Perl script which check connection to a oracle database running in a container . Here is my code
#!/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");
Using this script I'm able to connect with oracle database . But this script doesn't give any status output to my terminal . How can i check the script is connected to database?. I know bash has $? for checking the status of previously executed cmd. Do we have something similar in Perl?
Here is what i want Output "Successfully connected to Oracle-db" when the connection is OK and failed status when script can't connect to database
Note:This code give error status to my terminal. My Perl version is v5.16.3
The documentation for the connect()
method says this:
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.
So your code could be as obvious as:
my $dbh = DBI->connect(...);
if ($dbh) {
say 'Connection ok';
} else {
die "Connection error: $DBI::errstr";
}
However, you're using RaiseError => 1
, so your program will die
rather than returning undef
. So if your program gets past that line, you know the connection was successful.
my $dbh = DBI->connect(...);
say 'Connection ok';