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

dear monks

i would like to access the sql statement that is executed by a parameterised query. i am using mysql. i have seen this thread here

http://www.perlmonks.org/?node_id=874778

But i would like to get the sql statement whether there was an error or not. In other words, I would like to get the sql if the execution was successful too.

thanks for your help
  • Comment on getting the sql of a parameterised query

Replies are listed 'Best First'.
Re: getting the sql of a parameterised query
by roboticus (Chancellor) on Dec 04, 2010 at 20:11 UTC

    In the general case, it's irrelevant, for several reasons:

    • There's no requirement that the database sees a query with the statement and values integrated, and hence, no requirement for DBI to construct one. When a database supports precompilation and column binding, then the DBI placeholder is a good model of what's going on.
    • There's no requirement that DBI is even talking to an SQL database! It can be fronting for something else entirely.

    Since you can track the SQL you give to prepare and have access to the arguments you pass the execute function, I'd suggest just logging that in the event of an error. You could even replace the values yourself. Something like the naive:

    $ST=$DB->prepare($SQL); if (! $ST->execute(@args)) { $SQL=~s/\?/$_/ for @args; print "STATEMENT: $SQL\nERROR: $DBI::errstr\n\n"; }

    could be enough to do the trick. (Yes, it's buggy: for the same reasons that you don't just composite the SQL command and data values and execute it that way. But for debugging purposes, it should do just fine.)

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      thanks - it is just for debugging to write the statements in a log. I know i have access to all of the information but i was hoping i could get the sql from the dbi rather than preparing it myself.
Re: getting the sql of a parameterised query
by moritz (Cardinal) on Dec 04, 2010 at 20:00 UTC
Re: getting the sql of a parameterised query
by mje (Curate) on Dec 06, 2010 at 13:49 UTC

    Until I read the answer from roboticus I didn't even think you might have thought a driver replaced the placeholders with your parameters in the SQL string. The purpose of preparing a statement with parameters is that the database can parse the SQL once, may be compile it, build an execution plan, optimise it, cache it etc as in most cases the parameters won't affect this. Drivers generally pass the SQL string including placeholders to the database engine then pass the parameters separately afterwards. So long as you are using prepare/execute (and not do) you can access the SQL you passed to prepare with the Statement attribute and the parameters via the ParamValues, ParamTypes and ParamArrays.