in reply to Re: Perl oracle insert error handling
in thread Perl oracle insert error handling

Thanks for the suggestion and I 100% agree to it.

My database connection, inserting into database, committing record everything works

I will go with one problem at a time.

My very first and most important problem is to have WHILE IF ($sth->err) loop working..I have changed my initial code little bit to move further.

somehow code doesn't like 2 close $fh; in the code and still logfile says 1 row commited where zero rows inserted actually.

while ($row = $csv->getline ($fh)) { $SQL1 = "Insert into TAB1 (sample_date, server, first, n1, n2) values (?,?,?,?,?)"; $sth = prepare($SQL1) $sth -> execute($row[0], $row[1], $row[2], $row[3], $row[4]); if ($sth->err) { $rc=0; $dbAgent->rollback(); close $fh; } $rc++; } close $fh; $dbAgent->commit;

Replies are listed 'Best First'.
Re^3: Perl oracle insert error handling
by poj (Abbot) on Dec 23, 2014 at 17:35 UTC

    You only need to prepare the statements once

    #!perl use strict; use Text::CSV; use DBD::Oracle; my $csv = Text::CSV->new ( { binary => 1 } ) or die "Cannot use CSV: ".Text::CSV->error_diag (); my $dbh = dbh(); # connect my $SQL1 = "INSERT INTO TAB1 (sample_date, server, first, n1, n2) VALUES (?,?,?,?,?)"; my $sth1 = $dbh->prepare($SQL1); my $SQL2 = "INSERT INTO STATUS (sample_date,server,csv_file,row_count, +status) VALUES (sysdate,?,?,?,?)"; my $sth2 = $dbh->prepare($SQL2); my @csvFile = ('1.csv','2.csv','3.csv'); for my $file (@csvFile){ insertRecords($file); } $dbh->disconnect; sub insertRecords { my $file = shift; print "Working under $file\n"; open my $fh,'<',$file or die "$file : $!"; my $status = "SUCCESS"; my $server; my $rc = 0; while (my $row = $csv->getline ($fh)){ ++$rc; $server = $row->[1]; print join ",",@$row[0..4],"\n"; if ( $sth1->execute(@$row[0..4]) ){ # ok } else { $status = "FAILURE"; last; } }; if ($status eq 'FAILURE'){ $dbh->rollback; $rc = 0; print "ERROR - Rolled back $file\n"; } $sth2->execute($server,$file,$rc,$status); $dbh->commit; close $fh; } # connect sub dbh { my $host = "localhost"; my $sid = 'xe'; my $user = ''; my $pwd = ''; my $dsn = "dbi:Oracle:host=$host;sid=$sid"; my $dbh = DBI->connect($dsn, $user, $pwd, { AutoCommit => 0, }) or die "$!"; return $dbh }
    poj
      poj... thanks a TONE for this update.. it has really teach me many things and I'm currently testing my code with your suggestions. I can use most of the logic from it and need to do change as per requirements.

      EXCELLENT and I'm waiting to be expert in perl to give back to community

Re^3: Perl oracle insert error handling
by Anonymous Monk on Dec 23, 2014 at 23:57 UTC
    My database connection, inserting into database, committing record everything works

    Really? Then next time show us that code, since the code in the OP certainly doesn't work.