db connect

connecting to mysql database, usual procedures

Page 1 of 1

1 Replies - 1858 Views - Last Post: 04 April 2008 - 07:08 AM

#1 b_real   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 29-December 06

db connect

Posted 03 April 2008 - 01:15 PM

I need to connect to a mysql database in subroutines in different files (all located in the same directory). Instead of having the connection paramaters hard coded in each subroutine, is there a way to set the parameters in one file, call it something like dbconnect.pl, save it separately, and then include that file every time I need to connect to the database in my other files?

You can do something similar in PHP using the 'include' command, something like:

 
<?php
//connect to mysql server & database
include 'dbconnect.php';

$sql="INSERT INTO user (FirstName, LastName, Age)
VALUES.....etc etc...
?>



Ive tried using perls 'require' command, but im not yet familiar or comfortable with changing the @INC path (nor am I with creating .pm perl modules) which appears to be what I need to change to get perl to look for my dbconnect.pm if I create it.

Thinking there must be a standard way of connecting to a db where you only have to change the parameters once without having to go through your whole site.

Is This A Good Question/Topic? 0
  • +

Replies To: db connect

#2 girasquid   User is offline

  • Barbarbar
  • member icon

Reputation: 108
  • View blog
  • Posts: 1,825
  • Joined: 03-October 06

Re: db connect

Posted 04 April 2008 - 07:08 AM

Yes, there is. Here's how I usually do it:
config.pm:
package config;

use Exporter;
our @ISA = qw(Exporter);

our %config;
our @EXPORT = qw(%config);

%config = (
	dbName	=>	'bat',
	dbUser	=>	'foo',
	dbPass	=>	'bar',
);

1;


And here's the code inside a script that uses it:
#!/usr/bin/perl -w

use strict;
use DBI;

use config;
my $dbh;
$dbh = DBI->connect(
	"DBI:mysql:$config{dbName}:localhost",
	$config{dbUser},$config{dbPass},
	{RaiseError => 1},
	);


Was This Post Helpful? 1

Page 1 of 1