【问题标题】:Loop in database using perl使用perl在数据库中循环
【发布时间】:2018-07-18 12:46:00
【问题描述】:

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

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

【问题讨论】:

  • 你发布的是什么?它充满了废话。 use dbi;??? my $r=my$seq;??? stdin??? my $sth-&gt;finish;??? 2 { 但 3 }???
  • @ikegami 好的。你为什么不告诉我这有什么问题?
  • 您向我们展示的代码根本无法运行。请包括您正在使用的实际代码。 (当然,减去任何用户名和密码,但没有其他更改。)
  • 不,有一个额外的} 会阻止代码甚至编译。 (尽管在区分大小写的文件系统上,use dbi; 甚至会在此之前失败。)请编辑问题并复制并粘贴您的确切代码,缩进 4 个空格(您可以在粘贴后选择文本并在编辑器中按 {} 按钮这样做)所以它被格式化为一个代码块。
  • $ perl garbage.plgarbage.pl 第 25 行不匹配的右大括号,在行尾/garbage.pl 第 25 行语法错误,靠近“}”/garbage.pl 的执行因编译而中止错误。 (而且这甚至没有在严格模式下运行!)

标签: mysql perl loops


【解决方案1】:

数据库:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多