Che*_*eso 2 perl loops dynamic dbi while-loop
我正在尝试将表名传递给获取该表的所有字段名称的子,将它们存储到数组中,然后将该数组与另一个sql查询的fetchrow结合使用以显示这些字段中的数据.这是我现在的代码:
以表名作为参数的子调用示例:
shamoo("reqhead_rec");
shamoo("approv_rec");
shamoo("denial_rec");
Run Code Online (Sandbox Code Playgroud)
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...
}
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种方法来转换这个不必明确定义的东西....
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())
Run Code Online (Sandbox Code Playgroud)
Cha*_*ens 13
使用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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可能还需要设置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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13339 次 |
| 最近记录: |