我正在尝试将表名传递给获取该表的所有字段名称的子类,将它们存储到数组中,然后将该数组与另一个SQL查询的fetchrow结合使用以显示那些数据领域。这是我现在的代码:
以表名作为参数的子调用示例:
shamoo("reqhead_rec");
shamoo("approv_rec");
shamoo("denial_rec");
shamoo sub:
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())
答案 0 :(得分:12)
使用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;
答案 1 :(得分:2)
我想知道这种方法是否适用于空表。
获取列元数据的最安全方法不是查看返回的hashref的键(可能不存在),而是按规则播放并使用DBI提供的$ sth本身属性:
$sth->{NAME}->[i]
$sth->{NAME_uc}->[i]
$sth->{NAME_lc}->[i]
有关详细信息,请参阅DBI手册页的“元数据”部分。