質問

私は、その後、そのテーブルのすべてのフィールド名を取得し、配列にそれらを格納し、サブにテーブル名を渡すためにしようとしているが、これらのデータを表示するには、別のSQLクエリのをfetchRowと一緒にその配列を使用していますフィールド。ここで私は今持っているコードだ:

パラメータとしてテーブル名を持つサブ・コールの例:

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

shamooサブます:

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...
    }
}

私は明示的に定義する必要はありません。このNTO何かを有効にする方法を探しています....

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())
役に立ちましたか?

解決

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;

他のヒント

このメソッドは空のテーブルのために働くだろうかしらます。

列のメタデータを取得するための最も安全な方法は、(存在しない可能性があります)返されたハッシュリファレンスのキーを見てではなく、ルールでプレイするとDBIを使用しないように、それ自体がかなっ$の属性を提供しています

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

詳細については、DBIのmanページのメタデータを参照してください。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top