简体   繁体   English

在Perl脚本中检索MySQL数据

[英]Mysql data retriving in perl script

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

When I execute this code I am getting the result as 1 . 当我执行此代码时,我得到的结果为1 In database the data stored as: 在数据库中,数据存储为:

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

Why isn't it getting the right data? 为什么没有获得正确的数据?

You are printing the result of execute , not the actual database results. 您正在打印execute的结果,而不是实际的数据库结果。 You want to do something like this... 你想做这样的事情...

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

->execute returns just query result(0, 1, 0E0), but not resultset. -> execute仅返回查询结果(0,1,0E0),但不返回结果集。 As for me, best way is: 对于我来说,最好的方法是:

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

If you need bind vaiables, you can use selectall_arrayref also: 如果需要绑定变量,也可以使用selectall_arrayref:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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