> -----Original Message-----
> From: MECKLIN, JOE (ASI) [mailto:[EMAIL PROTECTED]]
> Sent: Tuesday, August 21, 2001 3:21 PM
> To: '[EMAIL PROTECTED]'
> Subject: DBI access inside a module
> 
> 
> I'm trying to open a database in my main program, pass 3 
> arguments to this
> module (list of field names, table name and additional SQL 
> arguments) then
> retrieve and forward the data to a waiting variable in the 
> main program.
> Every time I run it from a command line I get the following message:
> 
> Can't call method "prepare" on an undefined value at
> /usr/lib/perl5/5.6.0/DBGet.pm line 19.
> 
> (Running from a browser only returns a blank screen).  The 
> only way I can
> get it to work from this module is to uncomment the "our $dbh ..."
> statement.  As a subroutine in the main program it works 
> fine.  I need to
> have this as a module so I can call it from several webpages, 
> each one a
> separate Perl script.
> 
> My question is: how can I open the database once in the main 
> program and
> have it visible to this module?  I don't want to have to reestablish
> connections repeatedly for each query for dozens of concurrent users.
> 
> In the main program I do this:
> ...
> use DBGet;
> ...
> our $dbh = DBI->connect("dbi:mysql:dbname:","user","password");
> ...
> my ($lookup_colist) = build_lookup_table("clli", 
> "common_co_list", "order by
> clli");
> ...
> 
> Thanks in advance for your help.
> Joe Mecklin
> 
> ########## Program listing ###########
> package DBGet;
> require Exporter;
>  
> our @ISA = qw(Exporter);
> our @EXPORT = qw(build_lookup_table);
> our $VERSION = 0.01;
>  
> sub build_lookup_table
> {
> # $_[0] = list of fields to retrieve
> # $_[1] = table name to retrieve fields from
> # $_[2] = any additional arguments
>  
>  
> #our $dbh = DBI->connect("dbi:mysql:dbname:","user","password");
>     my $statement = "select $_[0] from $_[1]";
>     $statement .= " $_[2]" if $_[2];
>  
>     $sth = $dbh->prepare( "$statement" );                     
> <------ line
> 19 from error message
>     $sth->execute();
>  
>     return $sth->fetchall_arrayref();
> }
>  
> 1;

Every global variable lives in a package namespace. In your main program,
the $dbh variable is really $main::dbh. When you don't specifically supply
the package name, the current package is assumed. So, inside your module,
since you have the statement "package DBGet;", any references to $dbh
are really $DBGet::dbh.

There are several ways to handle this, including:

1. Continue to leave the global in one package or the other, and reference
by the fully-qualified name where necessary.

2. Pass the $dbh variable to the function call.

3. Create a method in DBGet to stash the $dbh value into a separate global.

4. Convert DBGet into a class and pass the $dbh to the class constructor.
That way each DBGet object could have its own $dbh.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to