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

See Tracing in DBI. The following works using DBD::SQLite but produces a lot of output:

$dbh->trace($dbh->parse_trace_flags('SQL|1|test'));

Output:

<- prepare('SELECT ... FROM ... WHERE ... = ?')= DBI::st=HASH(0x21ee924) at booklet-excel.pl line 213

<- execute('Inhaler')= '0E0' at booklet-excel.pl line 215

etc etc.

You could plug your own filter in to the trace stream to only keep prepares.


You can do a debug print of a prepared statement using the Statement attribute. This can be accessed either with a "statement handle" or a "database handle".

print $sth->{Statement} # with a statement handle

print $dbh->{Statement} # with a database handle

Not in general, because DBI doesn't necessarily produce such a query. If your database supports prepared statements and placeholders in its API, DBI will pass them through and let the database do the work, which is one of the reasons to use prepared statements.