从Perl中的数据库到电子表格

时间:2012-10-06 05:17:50

标签: perl

我有一个这样的交易表:

TransactionID    Date           AccountNumber   Type    Amount  
657520           02-07-1999     016901581432    Debit   16000  
657524           02-07-1999     016901581432    Debit   13000  
657538           09-07-1999     016901581432    Credit  11000  
657548           18-07-1999     016901581432    Credit  15500  
657519           02-07-1999     016901581433    Debit   12000  
657523           02-07-1999     016901581433    Credit  11000  
657529           03-07-1999     016901581433    Debit   15000  
657539           10-07-1999     016901581433    Credit  10000  
657541           11-07-1999     016901581434    Debit   12000  
657525           03-07-1999     016901581434    Debit   15000  
657533           05-07-1999     016901581434    Credit  12500 

我应该使用数据库中的SQL查询找到每个帐户的总借记和总贷方金额,并使用Perl将结果存储在电子表格中。

这是我的代码:

#!/usr/bin/perl
use DBI;
use strict;
use warnings;
use Spreadsheet::WriteExcel;
$dbh = DBI->connect('dbi:database','prithvi','prithvi') or die "Couldn't connect";
my $tran_cur = $dbh->prepare("SELECT AccountNumber, Type, SUM(Amount) FROM transaction GROUP BY AccountNumber, Type");
my $workbook = Spreadsheet::WriteExcel->new('results.xls');
my $worksheet = $workbook->add_worksheet('Result');
my $row = 0;
my $col = 0;
$worksheet->write_row($row++, $col, ['Account Number','Type','Total Amount']);
while( my @data = $tran_cur->fetchrow_array)
{
 $worksheet->write_row($row++, $col, \@data);
}

我在代码中哪里出错了?请帮忙。我只将Excel表格中的标题作为输出。

1 个答案:

答案 0 :(得分:2)

您需要在调用$tran_cur->fetchrow_array之前执行预准备语句:

$tran_cur->execute;