Self explanatory variables as the arguments to your sub would have avoided the need to explain what they are. Use gets executed at begin time. If you really don't want to load DBI every time the code runs use require. There is really no point in using strict in a 2 line sub. It is lexically scoped. Put it just under the shebang line.
This uses a closure to make a single persistent connection to the DB so you can get that connection from anywhere just by calling the sub. Call it a lightweight object. By adding a disconnect sub within the closure block you can just call that in an end block and your code will automatically disconnect on exit (including if it crashes). This will automatically prevent you from getting can't connect, too many connection errors (especially during testing).
{ my $dbh; sub rm_conn { my ($db, $user, $pass) = @_; require DBI; return $dbh if $dbh; # already connected $dbh = DBI->connect("DBI:Pg:dbname=$db;",$user,$pass, {'RaiseE +rror' => 1}) or die "Can't connect to $db $DBI::errstr; return $dbh; } sub dis_conn { $dbh->disconnect if $dbh; } } END { dis_conn() }
As far as storing usernames and passwords on the server a flat file is a simple as it gets. Write a sub that takes a filename, opens the file, reads the db/user/pass data in whatever format works for you and returns them. Then just pass it to your rm_conn sub. The name get_dbh makes more sense for self documentation than rm_conn (at least in english which may not be your language)
sub get_db_stuff { my ($filename) = @_; open F, $filename or die "Can't read $filename $!\n"; my $data = <F>; close F; # this split allows comma, tab or space separated data # but of course precludes spaces in the names my ($db,$user,$pass) = split /[,\s]+/, $data; die "Invalid $data in $filename!\n" unless $db and $user and $pass +; return ($db,$user,$pass); }
You could of course integrate that into your connection routine if desired.
For pre-rolled solutions have a look at DBIx::Password and DBIx::PasswordIniFile
In reply to Re: Database connection
by tachyon-II
in thread Database connection
by rooneyl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |