How can I print the SQL query executed after Perl's DBI fills in the placeholders?

Viewed 25081

I'm using Perl's DBI module. I prepare a statement using placeholders, then execute the query.

Is it possible to print out the final query that was executed without manually escaping the parameters and dropping them into the placeholders?

Thanks

8 Answers

For the majority of queries, the simplest debugging is to use the following...

  • If you prepare and execute a single statement using do method, use:

     use feature 'say';
     say $dbh->{Statement};
    
  • If you use prepare and execute methods separately, use:

     use feature 'say';
     use Data::Dumper;
     $Data::Dumper::Sortkeys = 1;
     say $sth->{Statement};
     say Dumper($sth->{ParamValues});
    

For perl neophytes, my solution, copied from not2qubit and simplified/hopefully made a bit more generic/reuseable:

sub dump_query {
  my $tquery = shift;
  my @args = shift;
  my $j;
    foreach my $j (@args) { $tquery =~ s/\?/\'$j\'/; }
    print STDERR "$tquery\n\n";
}
Related