LoginSignup
14
12

More than 5 years have passed since last update.

Perl : DBIで実行されたクエリをお手軽に見る

Last updated at Posted at 2015-05-18

前提条件:cpanm、dbi、mysqlがイントールされていること

DBIx::QueryLog をインストール

$ cpanm DBIx::QueryLog

使用例1:クラス全体のクエリを出したい場合

use DBIx::QueryLog;

querylog1.pl
use strict;
use warnings;
use utf8;
use DBI;
use DBIx::QueryLog;

my $dbh = DBI->connect('DBI:mysql:hoge_db', 'root', '');
my $sth;

# クエリ1
$sth = $dbh->prepare("SELECT * FROM hoge_table LIMIT ?");
$sth->execute(1);

# クエリ2
$sth = $dbh->prepare("SELECT * FROM hoge_table LIMIT 2");
$sth->execute();

# クエリ3
$sth = $dbh->prepare("SELECT id,name FROM hoge_table LIMIT 2");
$sth->execute();

1;

実行

$ perl querylog1.pl

結果

[2015-05-18T21:58:03] [main] [0.000209] SELECT * FROM hoge_table LIMIT 1 at querylog1.pl line 12
[2015-05-18T21:58:03] [main] [0.000103] SELECT * FROM hoge_table LIMIT 2 at querylog1.pl line 16
[2015-05-18T21:58:03] [main] [0.001153] SELECT id,name FROM hoge_table LIMIT 2 at querylog1.pl line 20

使用例2:一部のクエリを出したい場合

use DBIx::QueryLog ();
DBIx::QueryLog->begin;
ここが出力対象になる
DBIx::QueryLog->end;

querylog2.pl
use strict;
use warnings;
use utf8;
use DBI;
use DBIx::QueryLog ();

my $dbh = DBI->connect('DBI:mysql:hoge_db', 'root', '');
my $sth;

# クエリ1
$sth = $dbh->prepare("SELECT * FROM hoge_table LIMIT ?");
$sth->execute(1);

# クエリ2
DBIx::QueryLog->begin;
$sth = $dbh->prepare("SELECT * FROM hoge_table LIMIT 2");
$sth->execute();
DBIx::QueryLog->end;

# クエリ3
$sth = $dbh->prepare("SELECT id,name FROM hoge_table LIMIT 2");
$sth->execute();

1;

実行

$ perl querylog2.pl

結果

[2015-05-18T22:00:06] [main] [0.000123] SELECT * FROM hoge_table LIMIT 2 at querylog2.pl line 17

おまけ:結果をファイルに出力したい

querylog3.pl
use strict;
use warnings;
use utf8;
use DBI;
use DBIx::QueryLog;

open my $fh, '>>', 'tmp/query.log' or die $!;
$DBIx::QueryLog::OUTPUT = $fh;

my $dbh = DBI->connect('DBI:mysql:hoge_db', 'root', '');
my $sth = $dbh->prepare("SELECT id,name FROM hoge_table LIMIT 1");
$sth->execute();

1;

結果

$ cat tmp/query.log
[2015-05-18T22:05:03] [main] [0.000123] SELECT id,name FROM hoge_table LIMIT 1 at querylog3.pl line 12
14
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12