用于更新DB的脚本

时间:2016-12-14 06:19:05

标签: perl dbi

我有以下用于更新Oracle数据库的perl脚本。它的工作非常好;但是,我想知道如何简化这个脚本:

use DBI;
my $dbh;
my $bad_form = "text.txt";

open (OUT, $bad_form) or die "Could not open $bad_form";
while (<OUT>){
    chomp $_;
    my ($item_id, $description, $form_id_1, $form_id_3) = split(/\|/, $_);

    my $new_form_id_1 = form_1($form_id_1);
    my $new_form_id_3 = form_3($form_id_3);

    if ( $new_form_id_1 ne 'null' ){
            my $sql = "update item_table set form_id_1 = '$new_form_id_1' where item_id = '$item_id'";
            my $item = $dbh->prepare($sql) or (log_error("Couldn't prepare statement: " . $dbh->errstr) and return 2);
            $item->execute() or (log_error("Couldn't execute statement: " . $item->errstr) and return 2);
    }else{
            $form_id_1 = "correct value";
            $new_form_id_1 = "no updated";
    }

    if ( $new_form_id_3 ne 'null' ){
            my $sql = "update item_table set form_id_3 = '$new_form_id_3' where item_id = '$item_id'";
            my $item = $dbh->prepare($sql) or (log_error("Couldn't prepare statement: " . $dbh->errstr) and return 2);
            $item->execute() or (log_error("Couldn't execute statement: " . $item->errstr) and return 2);

    }else{
            $form_id_3 = "correct value";
            $new_form_id_3 = "no updated";
    }
}

使用函数form_1()和form_3()来为form_id_1,3生成新值。

任何帮助将不胜感激。非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

使用严格;

使用prepare()作为占位符,将您的两个while移出?循环。然后只调用execute($new_form_id_x, $item_id)以获取循环内适当的预处理语句句柄。