Ubuntu10.04でPerl5.10を実行していて、perlDBIモジュールを使用しています。PerlDBIのSQLクエリの「WHERE」句で「AND」条件を使用しようとしています。DBD::CSVドライバーを使用しています。
以下のtest.csvを検討してください。
OS,RELEASE,VERSION
Ubuntu,Warty,4
Ubuntu,Hoary,5
Ubuntu,Breezy,5
Fedora,Yarrow,1
Fedora,Tettnang,2
Fedora,Stentz,4
ここでは、FedoraStentzのバージョンを取得したいと思います。これが私のコードです:
#!/usr/bin/perl -w
use strict;
use DBI;
my $table = "test.csv";
my $dbh = DBI->connect ("dbi:CSV:") or die "Cannot connect to the CSV file: $DBI::errstr()";
$dbh->{RaiseError} = 1;
$dbh->{TraceLevel} = 0;
my $query = "select VERSION from $table where OS='Fedora' and RELEASE='Yarrow'";
my $sth = $dbh->prepare ($query);
$sth->execute ();
$sth->dump_results();
$sth->finish();
$dbh->disconnect();
これが出力です。
0 rows
以下のように実際の値の代わりにプレースホルダーをクエリで使用する場合:
my $query = "select VERSION from $table where OS=? and RELEASE=?";
my $sth = $dbh->prepare ($query);
$sth->execute ('Fedora', 'Yarrow');
$sth->dump_results();
$sth->finish();
$dbh->disconnect();
その場合、出力は次のようなエラーになります。
DBD::CSV::st execute failed: You passed 2 parameters where 0 required [for Statement "select VERSION from test.csv where OS=? and RELEASE=?"] at count.pl line 14.
DBD::CSV::st execute failed: You passed 2 parameters where 0 required [for Statement "select VERSION from test.csv where OS=? and RELEASE=?"] at count.pl line 14.
しかし、以下のようにWEHRE句で条件を1つだけ使用すると、スクリプトは正しい出力を提供します。
my $query = "select VERSION from $table where OS=?";
my $sth = $dbh->prepare ($query);
$sth->execute ('Fedora');
$sth->dump_results();
$sth->finish();
$dbh->disconnect();
そして、出力は次のとおりです。
'1'
'2'
'4'
3 rows
つまり、結論として、私の問題は、「where」句に「and」条件を書き込むと、機能しないということです。クエリ構文に何か問題があるのではないかと思いますが、まだそれを理解できていません。どんな指針や提案も大いに役立つでしょう。
また、同じ問題についてperlmonksに関する継続的なスレッドがあります:http://www.perlmonks.org/? node_id = 990214
ありがとう。