Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: prepare statement within DBI

by mpeppler (Vicar)
on Aug 25, 2004 at 15:29 UTC ( [id://385705]=note: print w/replies, xml ) Need Help??


in reply to prepare statement within DBI

Sending more than one SQL statement in a prepare() is in general not supported. Exceptions exist for databases such as Sybase and MS-SQL where multiple statements are supported natively by the server.

However, you could push the actual prepare/execute/fetch loop into a subroutine which would avoid the duplicated code (minimal and simplistic implementation):

my $row1 = fetch_count($dbh, "table_one"); my $row2 = fetch_count($dbh, "table_two"); print "$row1, $row2\n"; sub fetch_count { my $dbh = shift; my $table = shift; my $sth = $dbh->prepare("select count(*) from $table"); $sth->execute; my $row = $sth->fetch_arrayref; return $row->[0]; }
Michael

Replies are listed 'Best First'.
Re^2: prepare statement within DBI
by Smylers (Pilgrim) on Aug 26, 2004 at 14:27 UTC

    For most of the duplication you avoid with your fetch_count function, DBI has a built-in way of avoiding it: whenever you've got a query on which ->fetch_... is only invoked once, you can skip the separate ->prepare and ->execute by using a $db->select_... method.

    So the 4 active lines in your function become just 1:

    sub fetch_count { my ($db, $table) = @_; $db->selectrow_array("SELECT COUNT(*) FROM $table"); }

    It probably isn't worth writing a function for that, since there isn't that much duplication without it:

    my $row1 = $dbh->selectrow_array('SELECT COUNT(*) FROM table_one'); my $row2 = $dbh->selectrow_array('SELECT COUNT(*) FROM table_two');

    But you could always put it in some sort of loop:

    my ($row1, $row2) = map { $dbh->selectrow_array("SELECT COUNT(*) FROM $_") } qw<table_one table_two>;

    (By the way, I think your ->fetch_arrayref is a typo.)

    Smylers

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://385705]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-24 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found