An Introduction to Class::DBI - First Example 17

Example - And the winner is...

Using DBI

  • Setup

        use DBI;
    
        my $DBH = DBI::connect('dbi:pg', 'dbi_user', 'dbi_password);
    
        my $nominee_search = $DBH->prepare(
            'SELECT id FROM nomination WHERE year = ? and type = ?'
        );
    
        my $voter_count    = $DBH->prepare(
            'SELECT voter_id, nomination_id FROM vote WHERE nomination_id = ?'
        );
    
        my $update_winner  = $DBH->prepare(
            'UPDATE nominations SET takes_the_oscar = ? WHERE id = ?'
        );
    
  • The program

            $nominee_search->execute(1965, 'Best Editing');
    
            my $winner_id = 0;
            my $max_votes = 0;
    
            while (my $nominee = $nominee_search->fetchrow_hashref) {
                $votes = 0
    
                $voter_count->execute($nominee);
    
                while ($voter_count->fetchrow_hashref) {
                    $votes++;
                }
    
                if ($votes > $max_votes) {
                    $winner_id = $nominee;
                    $max_votes = $votes;
                }
            }
    
            if ($winner_id) {
                $update_winner->execute(1, $winner_id);
            }
    

 

YAPC::Canada << Previous | Index | Next >>
Copyright © 2003 Michael Graham