fetchrow_array()与fetchrow_arrayref()与fetchrow_hashref()的使用方法

fetchrow_array 
这个方法取下一行数据并且作为一个字段值数组返回它。范例:
while(@row = $sth->fetchrow_array) {
print qw($row[0]/t$row[1]/t$row[2]/n);
}
fetchrow_arrayref 
这个方法取下一行数据并且作为一个对一个字段值数组的引用返回它。范例:
while($row_ref = $sth->fetchrow_arrayref) {
print qw($row_ref->[0]/t$row_ref->[1]/t$row_ref->[2]/n);
}
fetchrow_hashref 
这个方法取一行数据并且返回包含字段名/值对的一个哈希表的一个引用。这个方法不如使用上述数组引用那样有效。范例:
while($hash_ref = $sth->fetchrow_hashref) {
print qw($hash_ref->{firstname}/t$hash_ref->{lastname}/t/
$hash_ref- > title}/n);
}

下面将详细介绍 用法,附有代码以及数据库表格

数据库表内容如下:

下面代码将会帮助你理解 三个函数的 具体使用  

#!/usr/bin/perl
use DBI;
my $host = "localhost";
my $driver ="mysql";
my $database = "catchdata";
my $dsn = "DBI:$driver:database=$database:$host";
my $userid ="root";
my $password = "root123";
my $dbh = DBI->connect($dsn,$userid,$password) or die $DBI::errstr;
my $sth3;

$sth3 = $dbh->prepare("select * from cmd_data");
$sth3->execute() or die $DBI::errstr;

print "---fetchrow_hashref的使用-----\n";
while($a = $sth3->fetchrow_hashref()){
print "$a->{'host'}\n";
print "$a->{'time'}\n";
print "$a->{'UID'}\n";
}

print "注意对比fetchrow_hashref()与 fetchrow_arrayref的引用方法\n";

print "-----fetchrow_arrayref的使用-------\n";
$sth = $dbh->prepare("select * from cmd_data");
$sth->execute() or die $DBI::errstr;

while(my $a1 = $sth->fetchrow_arrayref()){
print "$a1->[2]\n";
print "$a1->[1]\n";
print "$a1->[3]\n";
}

print "-----fetchrow_array的使用1-------\n";
my $sth1 = $dbh->prepare("select count(*)from cmd_data where host='HOST:10.1.1.5'");
$sth1->execute() or die $DBI::errstr;
my $record;
$record = $sth1->fetchrow_array();
print"\$record == $record\n";

print "-----fetchrow_array的使用22-------\n";
my $sth2 = $dbh->prepare("select * from cmd_data");
$sth2->execute() or die $DBI::errstr;
while( my @rows = $sth2->fetchrow_array()){
print("time:$rows[1]\n");
print("host:$rows[2]\n");
print("UID:$rows[3]\n");
}

运行结果如下   

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值