从PERL中的DBI语句转储准备的sql查询

Nov*_*der 7 debugging perl dump dbi

我在Perl中使用DBI连接到我的PostgreSQL数据库.一切正常,但在我的调试(打印结果等)中,我无法看到perls DBI模块准备的查询是否真的正确.

我有这样的事情:

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

在调用execute之后,我无法看到sql查询的外观,因为execute是将参数绑定到查询的最新步骤.

我希望有类似$sth->getLastExecutedQuery()或类似的东西来查看查询的样子.

在这种情况下,函数getLastExecutedQuery()将返回:

SELECT * FROM company WHERE companyname LIKE 'Company Name%' AND city = 'City name';
Run Code Online (Sandbox Code Playgroud)

有没有办法得到这个?它仅用于调试目的.

Lum*_*umi 6

使用DBI跟踪工具.它的工作原理如下:

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;
Run Code Online (Sandbox Code Playgroud)


Dav*_*idO 6

DBI支持以下内容:有DBI->trace($tracefile_handle)方法(跟踪所有DBI交互),或者$dbh->trace($tracefile_handle)只跟踪特定句柄上的交互.输出默认为STDERR,但通过提供$tracefile_handle,您可以显式地将输出发送到不同的文件(或只使用shell重定向).

DBD :: pg也支持$h->trace('SQL'); 这必须得到你的DBD驱动程序的支持才能工作,但幸运的是DBD :: Pg确实支持这个功能.

DBAN,CPAN - DBI以及CPAN上DBD :: Pg的文档- DBD :: Pg确实为您提供了有关跟踪的所有知识.


boh*_*ica 5

除了其他人提到的跟踪之外,你应该看一下https://metacpan.org/pod/DBI#Statement,它给你最后执行的SQL和https://metacpan.org/pod/DBI#ParamValueshttps:// metacpan .org/pod/DBI#ParamTypes告诉你你的参数.

还有DBIx :: Log4perl,它可以在没有所有DBI跟踪的情况下记录您想要的内容.