Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I have this code in my script and sometimes I would like to print for debugging the value of the SQL query that is been used, how could I do that from this;

my $sql = $dbh->exec_select( "select name,account from my_table where +name=?", $name );


I would like to print for debugging something like this from the code above;
select name,account from my_table where name=Joe


How could I do that?
Thanks!

Replies are listed 'Best First'.
Re: Printing SQL query in Perl
by Your Mother (Archbishop) on Jun 30, 2010 at 18:49 UTC

    Probably you want DBI->trace. See the DBI docs for the parameters/options.

Re: Printing SQL query in Perl
by mje (Curate) on Jul 01, 2010 at 08:28 UTC

    I'm assuming you want to do it for more than the one SQL statement you showed. I've no idea what exec_select is - it is not a DBI method but I presume at some stage in your code something calls the prepare and execute methods and you have that statement handle. You can use the Statement attribute to retrieve the SQL executed and the ParamValues attribute to get the bound parameters something like this:

    my $s = $h->prepare(q/select * from mje where a = ?/); $s->execute(1); my $sql = $s->{Statement}; my $pvals = $s->{ParamValues}; my $params = ''; foreach (keys %$pvals) { $params .= " $_ = $pvals->{$_}" } print "$sql $params\n"; # outputs select * from mje where a = ? 1 = 1

    Now if you look at DBI callbacks you can add a callback to the execute method and output whatever you like.

    However, I naturally find DBIx::Log4perl much more straight forward to as use as I wrote it.

Re: Printing SQL query in Perl
by Generoso (Prior) on Jun 30, 2010 at 21:21 UTC

    Try with this 2 lines instead of the one you have, it may give you more info on what is happening.

    my $sth = $dbh->prepare("select name,account from my_table where name= +?") || die $dbh->errstr; my $select_success = $sth->execute($name) || die $sth->errstr;
Re: Printing SQL query in Perl
by pajout (Curate) on Jul 01, 2010 at 11:44 UTC
    You can set DBI_TRACE env variable to 1 (or more for higher verbosity) and see error output of your script. See `man DBI` for details.
Re: Printing SQL query in Perl
by Anonymous Monk on Jul 02, 2010 at 19:33 UTC
    you can take the query in a variable and try printing the variable and use the same variable for executing.