使用perl在数据库中循环

时间:2018-02-08 03:41:55

标签: mysql perl loops

我需要从输入中提取每个字符(输入是数字)并在我的数据库中检查它,如果数字存在,则将打印相应的行。但是在我的代码中循环不起作用,只打印第一个字符。

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";`

1 个答案:

答案 0 :(得分:3)

数据库:

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)

代码:

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";
    }
};

输出:

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