Hallo Perlmonks,
I hope that someone might be able to point me in the right direction.
I want to query a small SQLite-Database into the while loop, but I can't fetch any data.
When I set manually the param $name_to_check, it's work fine; sure, I rewrite in this case any input data from the console (to test is ok).
I use Linux Fedora 15, Perl version: 5.12.x and SQLite: 3.7.5
The SQLite database have one table (name_tab) with two cols (name and age). For example:
Name Age
-------------------
Ana 25
George 20
Denis 21
Jim 28
Mily 22
I get no errors when the script runs and I can't find the origin of the problem.
#!/usr/bin/perl -W
use strict;
use DBI;
my ($sth,$dbh);
my $db_attr = {RaiseError => 1, PrintError => 1};
my $db_error = $DBI::errstr;
# Open the connector
my $name_db = '/opt/name.db';
$dbh = DBI->connect("dbi:SQLite:$name_db","","",$db_attr);
if (defined($db_error) && $db_error ne " ") {
print STDERR "Cannot connect to database $name_db: $db_error\n";
exit;
} # end if
# init
$| = 1;
# Prepare the SQL
my $query = "SELECT name,age FROM name_tab WHERE name = ?";
$sth = $dbh->prepare($query) or die "Couldn't prepare statement: " . $
+dbh->errstr;
# the main loop. I read the new line from the console, and fetch the r
+ow for this name
while (defined($name_to_check = <>)) {
# my $name_to_check = 'Denis'; # rewrite the entry, is working
$sth->execute($name_to_check) or die "Couldn't execute statement:
+" . $sth->errstr;
my ($name_from_db,$age) = $sth->fetchrow_array();
print "Fetched from SQLite: $name_from_db Age: $age\n";
}
# Disconect from SQLite
#-----------------------------------------------------------------
$dbh->disconnect();
exit 0;
Thanks in advance,
Josef