Connect to Oracle DB from Perl script
After successful installation of DBD::Oracle it’s time to use it. The connection string is the same as for he rest DB:
-
my $dbi = DBI->connect("dbi:Oracle:$db_name:$db_host:$db_port", $db_user, $db_pass);
As result of running code above I got following error:
Couldn’t connect to database db_name: ORA-12154: TNS:could not resolve the connect identifier specified (DBD ERROR: OCIServerAttach)
After googling I found that the problem was that. I tried to connect to the remove database but the driver couldn’t do that without special file – tnsnames.ora. It should be placed to the $ORACLE_HOME/network/admin and contain something like that:
-
db_name =
-
(DESCRIPTION =
-
(ADDRESS_LIST =
-
(ADDRESS = (PROTOCOL = TCP)(HOST = db_host)(PORT = db_port))
-
)
-
(CONNECT_DATA =
-
(SERVICE_NAME = db_name)
-
)
-
)
And the connection string should be changed to use service name from the tnsnames.ora instead of host:
-
my $dbi = DBI->connect("dbi:Oracle:$service_name", $db_user, $db_pass);
Finally we should export variable ORACLE_SID into our environment. Add this command into .bashrc
-
export ORACLE_SID="orcl"
or set it using Perl variable $ENV:
-
$ENV{ORACLE_SID} = ‘orcl’;
See also




