简体   繁体   中英

Loop in database using perl

I need to extract each character from the input (input are numbers) and check it against my database, if the number is present the corresponding rows will be printed. But in my code the loop doesn't work and only the first character is printed.

use dbi;
my $seq=<stdin>;
my $r=my$seq;
my $db="hnf1a";
my $user="root";
my $password="";
my $host="localhost";
my $dbh = DBI->connect("DBI:mysql:database=$db:$host",$user,$password);
my @w= split(//, $r);
print @w;
foreach my $b(@w)
{
my $sth=$dbh -> prepare("select an,ano from mody having ano = '$b' ");
my $rv=$sth->execute();
while (my @row =$sth->fetchrow_array())
{
print @row; 
}
}
my $rc=my $sth->finish;
}
print "database closed";`

Database:

mysql> select * from mody;
+----+---------+------+
| id | an      | ano  |
+----+---------+------+
|  1 | 123     | 456  |
|  2 | abc     | 567  |
|  3 | hello   | 5    |
|  4 | world   | 5    |
|  5 | goodbye | 6    |
+----+---------+------+
5 rows in set (0.00 sec)

Code:

use strict;
use warnings; 
use 5.020;
use autodie;
use Data::Dumper;
use DBI;

my $dsn = 'dbi:MariaDB:database=my_db;host=localhost';
my $dbh = DBI->connect($dsn, 'root', '');
my $sth = $dbh->prepare('SELECT an,ano FROM mody where ano = ?');

my $input = "56";
my @numbers = split //, $input;

for my $number(@numbers) {
    say "rows matching input <$number>:";

    $sth->execute($number);

    while(my @data = $sth->fetchrow_array) {
        say "\t@data";
    }
};

Output:

rows matching input <5>:
    hello 5
    world 5
rows matching input <6>:
    goodbye 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM