I have the following pretty complex Perl code that is fed by a dynamic array varying in size but typically between 10 and 20 rows. I'm therefore running this in a loop but reckon there must be a more elegant way of inserting the data.
Is it possible to improve this code to make it more efficient?
sub data_fill {
my $target = shift;
my (@input_data) = @_;
# Delete the old data
my $sth = $dbh->prepare("DELETE FROM work_data WHERE target = '$target' ");
$sth->execute();
# Insert the new data
my $sql = qq{INSERT INTO work_data (target, trackingno, temp, apple, orange, banana, strawberry, lettuce, apricot, peach, blackberry, melon, lemon) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)};
my $sth = $dbh->prepare($sql);
my $arraysize = scalar(@input_data);
my $i = 0;
while ($i < $arraysize) {
$sth->bind_param(1, $target, SQL_VARCHAR);
$sth->bind_param(2, 'OK', SQL_VARCHAR);
$sth->bind_param(3, $input_data[$i], SQL_VARCHAR);
$sth->bind_param(4, $input_data[$i + 1], SQL_VARCHAR);
$sth->bind_param(5, $input_data[$i + 2], SQL_VARCHAR);
$sth->bind_param(6, $input_data[$i + 3], SQL_VARCHAR);
$sth->bind_param(7, $input_data[$i + 4], SQL_VARCHAR);
my $lettuce = $input_data[$i + 5];
my $apricot = $input_data[$i + 6];
my $peach = $input_data[$i + 7];
if (length($lettuce) == 0) {
$lettuce = -1;
} # Safety net to help later in db sorting
if (length($apricot) == 0) {
$apricot = -1;
} # Safety net to help later in db sorting
if (length($peach) == 0) {
$peach = -1;
} # Safety net to help later in db sorting
$sth->bind_param(8, $lettuce, SQL_INTEGER);
$sth->bind_param(9, $apricot, SQL_INTEGER);
$sth->bind_param(10, $peach, SQL_INTEGER);
$sth->bind_param(11, $input_data[$i + 8], SQL_VARCHAR);
$sth->bind_param(12, $input_data[$i + 9], SQL_VARCHAR);
$sth->bind_param(13, $input_data[$i + 10], SQL_VARCHAR);
$sth->execute;
$i = $i + 11; # INCREMENT
}
$dbh->disconnect;
return;
}
sqlite_see_if_its_a_numberattribute so you don't have to callbind_parama million times and then simply pass the list of bind values toexecute, e.g.$sth->execute(@input_data);?