Add an item to a table from a tab delimited file with the table fields in the 1st row of the file:
## get data ##
open my $DAT, '<', $getfile or croak "cannot open $getfile";
my @data = <$DAT>;
close $DAT or croak 'cannot close data';
chomp @data;
## add data to mySQL table 'table' ##
my $sql = q~
INSERT INTO table ( item1, item2)
VALUES( ?, ? )
~;
my $dbh = WebDB::connect();
for my $i ( 1 .. $#data ) {
my ( $item1, $item2 ) = split /\t/xsm, $data[$i];
my $sth = $dbh->prepare($sql);
$sth->execute( $item1, $item2 );
}
$sth->finish();
$dbh->disconnect();
To update existing items in the table: (same data file as above)
my $sql = q~
UPDATE table SET item1 = ?, item2 = ?
WHERE item1 = ?
~;
my $dbh = WebDB::connect();
for my $i ( 1 .. $#data ) {
my ( $item1, $item2 ) = split /\t/xsm, $data[$i];
my $sth = $dbh->prepare($sql);
$sth->execute( $item1, $item2, $item1 );
}
$sth->finish();
$dbh->disconnect();
To simply open that table as an array (with selectors and sorted by a key):
my @datab;
my $sql = q~
SELECT table
FROM table
WHERE item1 = ? AND item2 = ?
ORDER by item1
~;
my $dbh = WebDB::connect();
my $sth = $dbh->prepare($sql);
$sth->execute( $item1, $item2 );
while ( my @val = $sth->fetchrow_array() ) {
push @datab, [@val];
}
$sth->finish();
$dbh->disconnect();
In this example, you can access the data in the array of arrays (@datab) by using:
for my $i (0 .. $#data) {
my ( $newitem1, $newitem2 ) = @{$datab[$i]};
##Do something with each 'row' in @datab ##
}