3

我试图将表名传递给一个获取该表的所有字段名的子程序,将它们存储到一个数组中,然后将该数组与另一个 sql 查询的 fetchrow 结合使用以显示这些字段中的数据。这是我现在拥有的代码:

以表名作为参数的子调用示例:

shamoo("reqhead_rec");
shamoo("approv_rec");
shamoo("denial_rec");

洗发水子:

sub shamoo
{
    my $table = shift;
    print uc($table)."\n=====================================\n";

    #takes arg (table name) and stores all the field names into an array
    $STMT = <<EOF;
    select first 1 * from $table
    EOF

    my $sth = $db1->prepare($STMT);$sth->execute;

    my ($i, @field);
    my $columns = $sth->{NAME_lc};
    while (my $row = $sth->fetch){for $i (0 .. $#$row){$field[$i] = $columns->[$i];}}

    $STMT = <<EOF;
    select * from $table where frm = '$frm' and req_no = $req_no
    EOF
    $sth = $db1->prepare($STMT);$sth->execute;
    $i=0;
    while ($i!=scalar(@field))
    {
    #need code for in here...
    }
}

我正在寻找一种方法来把它变成不需要明确定义的东西......

my ($frm, $req_no, $auth_id, $alt_auth_id, $id_acct, $seq_no, $id, $appr_stat, $add_date, $approve_date, $approve_time, $prim);
while(($frm, $req_no, $auth_id, $alt_auth_id, $id_acct, $seq_no, $id, $appr_stat, $add_date, $approve_date, $approve_time, $prim) = $sth->fetchrow_array())
4

2 回答 2

15

使用 fetchrow_hashref:

sub shamoo {
    my ($dbh, $frm, $req_no, $table) = @_;

    print uc($table), "\n", "=" x 36, "\n";

    #takes arg (table name) and stores all the field names into an array
    my $sth = $dbh->prepare(
        "select * from $table where frm = ? and req_no = ?"
    );

    $sth->execute($frm, $req_no);

    my $i = 1;
    while (my $row = $sth->fetchrow_hashref) {
        print "row ", $i++, "\n";
        for my $col (keys %$row) {
            print "\t$col is $row->{$col}\n";
        }
    }
}

您可能还希望设置FetchHashKeyName"NAME_lc""NAME_uc"在创建数据库句柄时:

my $dbh = DBI->connect(
    $dsn,
    $user,
    $pass,
    {
        ChopBlanks       => 1,
        AutoCommit       => 1,
        PrintError       => 0,
        RaiseError       => 1,
        FetchHashKeyName => "NAME_lc",
    }
) or die DBI->errstr;
于 2009-05-15T15:52:09.163 回答
2

我想知道这种方法是否适用于空表。

获取列元数据的最安全方法不是查看返回的 hashref 的键(可能不存在),而是按照规则进行操作并使用 DBI 提供的 $sth 本身的属性:

$sth->{NAME}->[i]
$sth->{NAME_uc}->[i]
$sth->{NAME_lc}->[i]

有关详细信息,请参阅 DBI 手册页的元数据部分。

于 2009-05-15T17:58:08.613 回答