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

前端 未结 8 656
梦毁少年i
梦毁少年i 2021-02-05 09:36

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 ma

相关标签:
8条回答
  • 2021-02-05 10:01

    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;
      say $sth->{Statement};
      say Dumper($sth->{ParamValues});
      
    0 讨论(0)
  • 2021-02-05 10:04

    As masto says in general the placeholders in the SQL are not directly replaced with your parameters. The whole point of parameterized SQL is the SQL with placeholders is passed to the database engine to parse once and then it just receives the parameters.

    As idssl notes you can obtain the SQL back from the statement or connection handle and you can also retrieve the parameters from ParamValues. If you don't want to do this yourself you can use something like DBIx::Log4perl to log just the SQL and parameters. See DBIX_L4P_LOG_DELAYBINDPARAM which outputs something like this:

    DEBUG - prepare(0.1): 'insert into mje values(?,?)'
    DEBUG - $execute(0.1) = [{':p1' => 1,':p2' => 'fred'},undef];
    

    Of course as it uses Log::Log4perl you can omit the "DEBUG - " if you want. There is a small tutorial for using DBIx::Log4perl here.

    You should be able to use DBIx::Log4perl with any DBD and if you cannot for some reason RT it and I will look at it.

    If you don't want to go with DBIx::Log4perl and the DBI trace options don't suit your needs you can write callbacks for DBI's prepare/select*/execute methods and gather whatever you like in them.

    0 讨论(0)
提交回复
热议问题