我在爲給定文件輸出正確數量的記錄時遇到問題。我的測試腳本只是執行到MySQL數據庫的perl dbi連接,並給出一個表的列表,提取(1)每個表的記錄。幫助使用perl dbi並創建唯一的輸出文件
對於我列出的每個表格,我還想打印出(1)記錄到其自己的文件。例如,如果我有一個100個表的列表,我應該預期每個100個獨立文件(1)個記錄。
到目前爲止,我能夠生成100個文件,但有超過(1)個記錄。該文件中有多達280條記錄。具有諷刺意味的是,我正在爲每條記錄生成一個唯一的密鑰,而密鑰是唯一的。
如果我將$data
打印到一個文件(在foreach循環之外),我得到了預期的結果,但是在一個文件中。例如,一個文件有100個記錄,但我想爲每個文件創建一個文件。
我似乎有一個問題,打開一個文件句柄,並正確地輸出它?或者我的代碼有其他錯誤。
有人可以告訴我如何正確設置它嗎?向我展示一些實現此目的的最佳實踐? 謝謝。
這裏是我的測試代碼:
# Get list of table
my @tblist = qx(mysql -u foo-bar -ppassw0rd --database $dbsrc -h $node --port 3306 -ss -e "show tables");
#Create data output
my $data = '';
foreach my $tblist (@tblist)
{
chomp $tblist;
#Testing to create file
my $out_file = "/home/$node-$tblist.$dt.dat";
open (my $out_fh, '>', $out_file) or die "cannot create $out_file: $!";
my $dbh = DBI->connect("DBI:mysql:database=$dbsrc;host=$node;port=3306",'foo-bar','passw0rd');
my $sth = $dbh->prepare("SELECT UUID(), '$node', ab, cd, ef, gh, hi FROM $tblist limit 1");
$sth->execute();
while (my($id, $nd,$ab,$cd,$ef,$gh,$hi) = $sth->fetchrow_array()) {
$data = $data. "__pk__^A$id^E1^A$nd^E2^A$ab^E3^A$cd^E4^A$ef^E5^A$gh^E6^A$hi^E7^D";
}
$sth->finish;
$dbh->disconnect;
#Testing to create file
print $out_fh $data;
close $out_fh or die "Failed to close file: $!";
};
#print $data; #Here if I uncomment and output to a single file, I can see the correct number of record, but its in (1) file
請你詳細說明一下嗎?怎麼樣? thx – cjd143SD 2011-02-25 17:35:09
謝謝你清理那個。它現在工作正常。 – cjd143SD 2011-02-25 17:42:56
還有一個問題,是否可以將創建文件的代碼分離到它自己的子例程中?如果是這樣,那麼將如何使用'$ data'?再次感謝。 – cjd143SD 2011-02-25 18:30:46