Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump prepared sql query from DBI statement in PERL

im using DBI in Perl to connect to my PostgreSQL Database. Everything is working fine but in my debugging (printing results etc.) iam not able to see if the query prepared by perls DBI module is really correct.

I have something like this:

$sth->prepare( qq{SELECT * FROM company WHERE companyname LIKE ? AND city = ?});
$sth->execute( $name.'%', $city);

Iam not able to see how the sql query looks after calling execute, as execute is the latest step where parameters are binded to the query.

I would like to have something like $sth->getLastExecutedQuery() or something to see how the query looked like.

In this case the function getLastExecutedQuery() would return:

SELECT * FROM company WHERE companyname LIKE 'Company Name%' AND city = 'City name';

Is there any way to get this? Its only for debugging purposes.

like image 932
NovumCoder Avatar asked May 04 '11 15:05

NovumCoder


People also ask

How do I write a query in Perl?

To query Vertica using Perl: Prepare a query statement using the Perl DBI module's prepare function. This function returns a statement handle that you use to execute the query and get the result set. Execute the prepared statement by calling the execute function on the statement handle.


2 Answers

DBI supports the following: There is the DBI->trace($tracefile_handle) method (traces all DBI interactions), or $dbh->trace($tracefile_handle) which would trace just the interactions on a specific handle. Output defaults to STDERR, but by supplying $tracefile_handle, you can explicitly send output to a different file (or just use shell redirection).

DBD::pg also supports $h->trace('SQL'); This must be supported by your DBD driver to work, but fortunately DBD::Pg does support the feature.

The documentation for DBI, at CPAN - DBI, and for DBD::Pg at CPAN - DBD::Pg really gives you all you need to know on tracing.

like image 74
DavidO Avatar answered Oct 02 '22 01:10

DavidO


Use the DBI tracing facility. It works like this:

use strict;
use warnings;
use DBI;
my %opt = ( RaiseError => 1 );
my $dbh = DBI->connect( 'dbi:mysql:test', 'fred', 'secret', \%opt );
$dbh->trace(2); # level 2 shows statement with inserted parameters
my $sql_i = 'insert into t1 (a, b) values ( ?, ? )';
my $sth_i = $dbh->prepare( $sql_i );
for ( qw/ eins zwei drei / ) {
    $sth_i->execute( $_, $_ );
}
$dbh->disconnect;
like image 40
Lumi Avatar answered Oct 01 '22 23:10

Lumi