在perl脚本中检索Mysql数据

时间:2013-09-05 12:22:54

标签: mysql perl

Connect with mysql and retrive data from the table.

  my $db ="JJusers";
  my $user ="root";
  my $password ="abcdef";
  my $host ="localhost";

  my $dbh =DBI->connect("DBI:mysql:$db:$host",$user,$password);

  my $uDt = $dbh->prepare("select Username,Password from Users");
  my $rv = $uDt->execute;

  print "<script>alert($rv)</script>";

当我执行此代码时,我得到的结果为1。在数据库中,数据存储为:

1, jj, pp(SNO, USERNAME,PASSWORD)

为什么不能获得正确的数据?

2 个答案:

答案 0 :(得分:4)

您正在打印execute的结果,而不是实际的数据库结果。你想做这样的事......

while (my @data = $rv->fetchrow_array()) {
    my $username = $data[0];
    my $password = $data[1];
    // ...
}

答案 1 :(得分:0)

- &gt; execute只返回查询结果(0,1,0E0),但不返回结果集。 至于我,最好的方法是:

my $res = $dbh->selectall_arrayref('select Username,Password from Users', {Slice=>{}});
# now, you can iterate result.
# for example:
foreach my $row(@$res) {
    print $row->{Username};
}

如果你需要绑定vaiables,你也可以使用selectall_arrayref:

my $res = $dbh->selectall_arrayref('select Username,Password from Users where id = ?',
    {Slice=>{}}, 1
);