in reply to SQL INSERT creator

Ever thought about (ab)using interpolation and the list-seperator variable to simplify things visually? Or perhaps some rudimentary checking of expected arguments?

  sub insert {      # Untested, but you get the idea ...

      my $dbh     = shift or warn("No database handle"), return;
      my $table   = shift or warn("No table given"),     return;
      my @columns = @_    or warn("No columns given"),   return;

      my $sql;
      {
          local $"    = ","; # interpolation voodoo :-)

          my @values  = ("?") x @columns;
          $sql        = "INSERT INTO $table (@columns) VALUES (@values)"; # s/my //
      }

      $dbh->prepare($sql) or die("Couldn't prepare $sql " . $dbh->errstr);

  }

    --k.

Update: per extremely below, because they've got a point. :-)


Replies are listed 'Best First'.
Re: Re: SQL INSERT creator
by extremely (Priest) on Dec 28, 2000 at 15:23 UTC
    Ouch, did you just change $" and pass that change on to DBI? What say you localize that a bit more local. =)
    my $sql; { my @values = ('?') x @columns; # I love that, BTW... local $" = ','; $sql = "INSERT INTO $table (@columns) VALUES (@values)"; } $dbh->prepare($sql) or die("Couldn't prepare $sql " . $dbh->errstr);

    Sure, the likelyhood of any of the DBI/DBD stuff using a string-interpolated array is pretty low but it is still bad practice.

    --
    $you = new YOU;
    honk() if $you->love(perl)