我正在使用 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)
我知道发生这种情况是因为我使用的是 hash,但是如果我只使用数组,我还能如何取回列名?我想要做的就是为任何任意查询得到类似的东西:
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;