perl多线程实例(四个线程同时读MYSQL数据库获取记录)

前端之家收集整理的这篇文章主要介绍了perl多线程实例(四个线程同时读MYSQL数据库获取记录)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
use threads;
use DBI();


# input:
# $_[0]: fruitname
sub fetchFruit {
     # Connect to the database.
    my $dbh = DBI->connect("DBI:MysqL:database=FruitDB;host=localhost","username","password",{'RaiseError' => 1});
     
     # Now retrieve data from the table.
    my $sth = $dbh->prepare("SELECT * FROM fruit where name = '".$_[0]."'");
    $sth->execute();
    while (my $ref = $sth->fetchrow_hashref()) {
       print "Found a row: name = $ref->{'name'},variety = $ref->{'variety'}\n";
    }
    $sth->finish();


    # Disconnect from the database.
    $dbh->disconnect();
}


my @arr = qw(APPLE ORANGE PEAR BANANA);
my @threads;
foreach (@arr) {
   push @threads,threads->new(\&fetchFruit,$_);
}
foreach (@threads) {
   $_->join();
}

猜你在找的Perl相关文章