Name

do

Synopsis


$rc  = $dbh->do($statement)           || die $dbh->errstr;
$rc  = $dbh->do($statement, \%attr)   || die $dbh->errstr;
$rv  = $dbh->do($statement, \%attr, @bind_values) || ...

Prepares and executes a single statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known or is not available.

This method is typically most useful for non-SELECT statements that either cannot be prepared in advance (due to a limitation of the driver) or do not need to be executed repeatedly. It should not be used for SELECT statements because it does not return a statement handle (so you can’t fetch any data).

The default do method is logically similar to:

sub do {
    my($dbh, $statement, $attr, @bind_values) = @_;
    my $sth = $dbh->prepare($statement, $attr) or return undef;
    $sth->execute(@bind_values) or return undef;
    my $rows = $sth->rows;
    ($rows == 0) ? "0E0" : $rows; # always return true if no error
}

For example:

my $rows_deleted = $dbh->do(q{
    DELETE FROM table
    WHERE status = ?
}, undef, 'DONE') || die $dbh->errstr;

Using placeholders and @bind_values with the do method can be useful because it avoids the need to correctly quote any variables in the $statement. But if you’ll be executing the statement many times, then it’s more efficient to prepare it once and call execute many times instead.

The q{...} style quoting used in this example avoids clashing with quotes that may be used in the SQL statement. Use the double-quote-like qq{...} operator ...

Get Programming the Perl DBI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.