【问题标题】:Perl DBI: Outputting different table values and saving themPerl DBI:输出不同的表值并保存它们
【发布时间】:2015-02-28 07:59:04
【问题描述】:

我的代码如下所示:

use DBI;
$dbh = DBI->connect( 'dbi:XYZ:ABC','ABCD', 'XXXX' )
or die "Connection Error: $DBI::errstr\n";

my $sth = $dbh->prepare('select "Tablespace" from <TABLE>')
or die "Couldn't prepare statement: " . $dbh->errstr;
$dbh->errstr;
$sth->execute
or die "Can't execute SQL statement: $DBI::errstr\n";

my @schemaname;
my @schematable;
while (@schemaname = $sth->fetchrow_array()){
print "SchemaName is: @schemaname\n";
$schematable[0][0]= $schemaname[0];
$schematable[1][0]= $schemaname[1];
$schematable[2][0]= $schemaname[2];
$schematable[3][0]= $schemaname[3];
$schematable[4][0]= $schemaname[4];

}
warn "Data fetching terminated early by error: $DBI::errstr\n"
if $DBI::err;
print($schematable[0][0]);
print($schematable[1][0]);
print($schematable[2][0]);
print($schematable[3][0]);
print($schematable[4][0]);
$sth->finish();
$dbh->disconnect;

我在这里尝试做的是从 SQl 数据库输出,但将其保存在一个数组中,以便我可以使用该数据生成警报。我不断从最后 7 行获得相同的字符串。此外,当我尝试使用数据库中的其他代码来保存数字时:

my $ssth = $dbh->prepare("SELECT STORAGE FROM database")
or die "Couldn't prepare statement: " . $dbh->errstr;
$dbh->errstr;
$ssth->execute
or die "Can't execute SQL statement: $DBI::errstr\n";

my @usedschemaspace;
while (@usedschemaspace = $ssth->fetchrow_array( )){
print "Used Schema space: @usedschemaspace\n";
$us= $usedschemaspace[0];
$schematable[0][1]= $schemaname[0];
$schematable[1][1]= $schemaname[1];
$schematable[2][1]= $schemaname[2];
$schematable[3][1]= $schemaname[3];
$schematable[4][1]= $schemaname[4];

}
warn "Data fetching terminated early by error: $DBI::errstr\n"
if $DBI::err;

$ssth->finish();
$sth->finish();
print($schematable[2][1]);
print($schematable[2][2]);
.....

从数据库断开

$dbh->disconnect;

在上述两种情况下,除了存储在 schematable[i][j] 中的最后一个变量之外,我什么都看不到。有什么明显的我做错了吗?

【问题讨论】:

    标签: sql perl dbi


    【解决方案1】:

    参考您发布的第一个帖子,我发现有两件事对我来说非常突出:

    my $sth = $dbh->prepare("SELECT "Tablespace" FROM <TABLE>")
    

    while (@schemaname = $sth->fetchrow_array()){
    

    您只在 SQL 查询(“表空间”)中请求一个变量,因此将 $sth->fetchrow_array() 的输出分配给 @schemaname 将导致 @schemaname 仅在 $schemaname[0 ].

    当您运行第一个代码块时,您的输出究竟是什么样的?

    如果您尝试将所有返回值保存到一个数组中,请尝试这样的操作。

    my $i=0;
    while(my ($schema_name) = $sth->fetchrow_array()) {
        $schematable[$i++][0] = $schema_name;
    }
    
    #blah blah blah
    
    $i=0;
    while(my ($used_schema_space) = $ssth->fetchrow_array()) {
        $schematable[$i++][1] = $used_schema_space;
    }
    

    我不确定您为什么要在最后打印 $schematable[2][2],因为您从未在脚本的早期定义它。

    我希望这会有所帮助...我不能 100% 确定您尝试使用哪种数据结构或您打算实现什么。

    【讨论】:

    • 嗨伊恩,感谢您指出这一点。为了回答您的问题并正确看待问题,我想输出我在数组中提到的 SQL 查询的两列,然后根据存储的值生成警报(电子邮件)。
    • 另外,我只是出于测试目的而尝试打印它以查看是否捕获了该值..
    猜你喜欢
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多