devxlogo

Connect to the DB for Multiple .cgi Web Services with PERL

Connect to the DB for Multiple .cgi Web Services with PERL

Most Web-based Perl applications use more than five .cgi Perl scripts. Instead of typing all the DBI information in the script, I created a function you can use that gets the information from a .dat file on the server, and parses it for the DBI.

It’s much more secure, since you’re not hand-typing DB login information on the script.

Here is the package script:

################ connectsql.pl #####################################################3#!c:/perl/bin/perl.exepackage connectsql;use Exporter;our @ISA = qw (Exporter);our @EXPORT = qw (connectsql $config{'dbUser'} $config{'dbServer'} $config{'dbPass'} $config{'datasource'});sub connectsql{use DBI; our $a; our $b; our $c; our $d; our %config; open FILE, "config.dat" or die "Can not open file.txt $!
"; while () {    chomp;      ($a,$b,$c,$d) = split(/:/); } $config{'dbServer'} = $b; $config{'dbUser'} = $a; $config{'dbPass'} = $d; $config{'dbName'} = $c; $config{'dataSource'} = "DBI:mysql:$config{'dbName'}:$config{'dbServer'}"; our $dbh = DBI->connect($config{'dataSource'},$config{'dbUser'},$config{'dbPass'}) || die"error"; 		 }

Now, all you need to do is add this to your code before the DBI connection:

...........require "connectsql.pl";&connectsql::connectsql();my $dbh = DBI->connect($connectsql::config{'dataSource'},$connectsql::config{'dbUser'},$connectsql::config{'dbPass'}) || die"error"; 	............

The config.dat file is easy:

################config.dat###############username:host:databasename:password:
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist