Dynamically build SQL statements for Perl DBI

| No Comments | No TrackBacks
I like to use join and map in order to cut down on too much static code and to simplify building SQL statements to pass to DBI.  Ideally, some sort of database abstraction should be used, but it is not always an option.

Below is an example block of code that handles a CGI form submission with an action of "Add" or "Update".  The SQL is built according to the action and passed to a single prepare and execute.
my $sql;
my @fields = qw(field1 field2 field3 field4 field5);
my @bind_values;
if ($input->{action} eq "Add") {
  $sql =
  "INSERT INTO datatable (" .
    join(", ", @fields) .
  ") VALUES (" .
    join(", ", map {"?"} @fields) .
  ")";
  map {push @bind_values, $input->{$_} } @fields;
}
elsif ($input->{action} eq "Update") {
  $sql =
    "UPDATE datatable SET " .
      join(", ", map {"$_ = ?"} @fields) .
    " WHERE primarykey = ?";
  map { push @bind_values, $input->{$_} } @fields;
  push @bind_values, $input->{primarykey};
}

if (length $sql) {
  my $sth = $dbh->prepare($sql);
  $sth->execute(@bind_values);
}

No TrackBacks

TrackBack URL: http://www.coderfoo.com/cgi-bin/mt/mt-tb.cgi/4

Leave a comment

Pages

About this Entry

This page contains a single entry by Andy published on July 9, 2009 11:50 AM.

Recursively find files containing carriage returns was the previous entry in this blog.

Resolving Subversion merge conflicts is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.261