Updating lots of database fields in a single row

Mark Fowler mark at twoshortplanks.com
Wed Jan 23 01:05:50 GMT 2013

On Tuesday, January 22, 2013, Philip Skinner wrote:

my $qry = $self->dbh->prepare("UPDATE table SET " . join (sort(@fields),
> '=?, ') . " WHERE id=?");
> my $affected = $qry->execute(@hash{sort(keys %hash)}, $id);

I know this is just demoing how to use hash manipulation to get two matched
lists, but I thought it might be worth pointing out to beginners that the
above code neglects error checking.

You should always check that dbh, prepare and execute all return errors and
handle them correctly. Or, alternatively turn on exception throwing when
you make the call to dbh using RaiseError:

    my $dbh = DBI->connect(
      { RaiseError => 1 },

Which is what I do in my subroutine that gets my database connection.

More information about the london.pm mailing list