tel2 has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks,
I've just written my first (significant) package, which is intended to centralise connections to a database, and the running of queries against it.
Here's script1.pl, which is the first of several scripts which will call the package:
#!/usr/bin/perl use crsTools4; connect2db; # Test query using $sth run_sql("SELECT * FROM person WHERE firstname = 'Joe'"); while ((@f) = $sth->fetchrow()) { print "@f\n" } # Test query using $sth2 (though I could just reuse $sth in this case) run_sql("SELECT * FROM person WHERE firstname = ? AND surname = ?",2,' +Joe','Bloggs'); # while ((@f) = $sth2->fetchrow()) while ((@f) = $sth->fetchrow()) { print "@f\n" }
And here's the package (filename crsTools4.pm):
package crsTools4; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(connect2db run_sql); # Symbols to be exported by defa +ult our @EXPORT_OK = qw($dbh $sth); sub connect2db { require DBI; our $dbh = DBI->connect("DBI:mysql:database=crs;host=127.0.0.1 +", 'crs_user', 'mypw') or die('Could not connect!'); } # Execute an SQL command (arg 1), with an optional specified handle # # (arg 2), and optional bind variables (args 3...). sub run_sql { my ($sql, $n) = (shift @_, shift @_); print "sql=\"$sql\", sth$n, bind=\"" . join(',',@_) . "\"\n"; # $$sth = $dbh->prepare($sql); # $$sth->execute(@_) or die "Could not execute: $DBI::errstr\n +"; # To make things simple while debugging, let's just hard-code +$sth $sth = $dbh->prepare($sql); $sth->execute or die "Could not execute: $DBI::errstr\n"; } 1; # Required for all packages, to return a true value
And, here's the output, complete with error message:
sql="SELECT * FROM person WHERE firstname = 'Joe'", sth, bind="" Can't call method "fetchrow" on an undefined value at ./test4.pl line +9.
As you can see, it fell over on the first query. Any ideas what I'm doing wrong? I assume it's to do with localisation of $sth or something (though I tried to make it global), but after a lot of trial and error, I'm ready to take advice from the experts...please.
Thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Errors from a simple Package
by Eliya (Vicar) on Mar 16, 2011 at 10:58 UTC | |
|
Re: Errors from a simple Package
by wfsp (Abbot) on Mar 16, 2011 at 09:50 UTC | |
|
Re: Errors from a simple Package
by tel2 (Pilgrim) on Mar 17, 2011 at 00:39 UTC | |
by runrig (Abbot) on Mar 17, 2011 at 01:14 UTC | |
by tel2 (Pilgrim) on Mar 17, 2011 at 22:02 UTC | |
|
Re: Errors from a simple Package
by runrig (Abbot) on Mar 17, 2011 at 01:18 UTC | |
by tel2 (Pilgrim) on Mar 17, 2011 at 22:14 UTC | |
by runrig (Abbot) on Mar 17, 2011 at 23:44 UTC | |
by tel2 (Pilgrim) on Mar 18, 2011 at 21:13 UTC |