我正在尝试使用 Perl 和 DBI 模块从 SQL Server 数据库中读取数据。我的意图是读取数据并将其打印到文本文件中(逗号分隔)。当我这样做时,我得到这样的结果:
var1,var2,var3
40406,20 ,783
50230,78 ,680
50230,78 ,680
50230,78 ,680
50230,78 ,680
所以第二个变量数据和逗号之间有一个空格。我尝试使用下面的代码对其进行修整,但没有奏效。我应该如何修改我的代码以摆脱那些空格?
我的代码在这里:
#!/bin/perl
use warnings;
use strict;
use DBI;
sub trim;
my $dbs = "dbi:ODBC:DRIVER={SQL Server};SERVER={xxxx}";
my ($username, $password) = ('un', 'pwd');
my $dbh = DBI->connect($dbs, $username, $password)
or die "Can't connect to $dbs: $DBI::errstr";
my $sth = $dbh->prepare("select var1, var2, var3 from db.dbo.table")
or die "Can't prepare statement: $DBI::errstr";
$sth->execute();
my $outfile = 'temp.txt';
open OUTFILE, '>', $outfile or die "Unable to open $outfile: $!";
print OUTFILE join(",", @{$sth->{NAME}}), "\n";
while (my @re = $sth->fetchrow_array) {
print OUTFILE join(",", trim(@re)), "\n";
}
close OUTFILE;
$sth->finish();
$dbh->disconnect();
############## subroutines ##################
sub trim($) {
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}