gpt4 book ai didi

Perl DBI 动态 fetchrow while 循环

转载 作者:行者123 更新时间:2023-12-03 08:30:18 28 4
gpt4 key购买 nike

我试图将表名传递给获取该表的所有字段名的子程序,将它们存储到一个数组中,然后将该数组与另一个 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())

最佳答案

使用 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;

关于Perl DBI 动态 fetchrow while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/869316/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com