DBIを使用してSQLite3データベースにクエリを実行しています。私が持っているものは機能しますが、列が順番に返されません。例:
Query: select col1, col2, col3, col4 from some_view;
Output:
col3, col2, col1, col4
3, 2, 1, 4
3, 2, 1, 4
3, 2, 1, 4
3, 2, 1, 4
...
(values and columns are just for illustration)
ハッシュを使用しているためにこれが発生していることはわかっていますが、配列のみを使用している場合、他にどのようにして列名を元に戻すことができますか?私がやりたいのは、任意のクエリに対して次のようなものを取得することです。
col1, col2, col3, col4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
...
(つまり、出力が正しい順序で列名が付いている必要があります。)
私はPerlの初心者ですが、これは単純な問題だと本当に思っていました。(これは以前にRubyとPHPで行ったことがありますが、Perlのドキュメントで探しているものを追跡するのに問題があります。)
これが私が現在持っているものの簡素化されたバージョンです:
use Data::Dumper;
use DBI;
my $database_path = '~/path/to/db.sqlite3';
$database = DBI->connect(
"dbi:SQLite:dbname=$database_path",
"",
"",
{
RaiseError => 1,
AutoCommit => 0,
}
) or die "Couldn't connect to database: " . DBI->errstr;
my $result = $database->prepare('select col1, col2, col3, col4 from some_view;')
or die "Couldn't prepare query: " . $database->errstr;
$result->execute
or die "Couldn't execute query: " . $result->errstr;
###########################################################################################
# What goes here to print the fields that I requested in the query?
# It can be totally arbitrary or '*' -- "col1, col2, col3, col4" is just for illustration.
# I would expect it to be called something like $result->fields
###########################################################################################
while (my $row = $result->fetchrow_hashref) {
my $csv = join(',', values %$row);
print "$csv\n";
}
$result->finish;
$database->disconnect;