Perl的DBI动态fetchrow while循环
-
22-08-2019 - |
题
我试图表名传递给获取该表的所有字段名,并将其存储到一个数组,然后子使用该阵列中的与另一个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...
}
}
我要寻找一种方法来把这个n要的东西,不必明确定义.... 结果
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;
其他提示
不知这种方法会为空表工作。
要获得列元数据的最安全的方法是不看返回hashref的键(这可能不存在),但按规则宁愿玩,并使用DBI提供的$属性某物本身:
$sth->{NAME}->[i]
$sth->{NAME_uc}->[i]
$sth->{NAME_lc}->[i]
请参阅所述DBI手册页的元数据部分的详细说明。
不隶属于 StackOverflow