zoukankan      html  css  js  c++  java
  • Perl working with mysql

    Previous Page Next Page

    17.5. Statements that Don't Return Anything

    17.5.1. The do() method

    The do() method is used to prepare and execute nonselect, nonrepeating statements in one step. Statements such as the UPDATE, INSERT, or DELETE are examples of SQL statements that would use the do method. These statements change the database but don't return data. Unlike the prepare method, do doesn't return a statement handle but instead returns a count of the number of rows that were affected and undef if the query failed. The do() method returns a count of the number of rows that were affected and undef if the query failed. (A return value of -1 means the number of rows is not known, not applicable, or not available.)

    $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
    

    The only drawback is performance if you are repeating an operation a number of times with placeholders, as we did in Example 17.39, because then, for each query the steps of prepare and execute must also be repeated over and over again.

    Adding Entries

    To add entries to a table in the database, the SQL INSERT statement is used in the DBI do method. The do method will return the number of new entries or undef if it fails.

    Example 17.40.
      use DBI;
      my $dbh=
           DBI->connect("DBI:mysql:host=localhost;user=root,
                      password=quigley1;
                      database=sample_db");
      # Add two new entries
    1  $dbh->do("INSERT INTO teams(name,wins,losses)
                  VALUES('San Francisco Fogheads', 24,12)");
    
    2  $dbh->do(qq/INSERT INTO teams(name, wins, losses)
             VALUES(?,?,?)/, undef,"Middlefield Monsters", 2, 32);
    
       $dbh->do(qq/INSERT INTO teams(name, wins, losses)
             VALUES(?,?,?)/, undef,"Littleton's Tigers", 4, 18);
    
    3  $dbh->do("INSERT INTO coaches
                  VALUES('','Roger Outback','San Francisco Fogheads',
                         'Defensive Coach','2006-03-16'");
    
     my $dbh->disconnect();
    

    Explanation

    1, 2, 3 The DBI do method is used to insert values into the teams table in the sample_db database. The prepare and execute methods are absent here, because do does it all. It returns the number of rows affected.

    Deleting Entries

    In the following example, a record is deleted if some condition is true. Since the delete method doesn't return a result set, it is called with the DBI do method.

    Example 17.41.
       use DBI;
       my $driver="DBI:mysql";
       my $database="sample_db";
       my $user="root";
       my $host="localhost";
    
       my $dbh = DBI->connect("$driver:database=$database;
           host=$host;user=$user") or die "Can't connect: " . DBI->errstr;
    
       print "Enter the team name you want to delete: ";
       chomp($name=<STDIN>);
    1  my $sth=$dbh->prepare('SELECT count(*) from teams WHERE name = ?');
    2  $sth->execute($name);
    3  print "Number of rows to be deleted: ", $sth->fetchrow_array(), "\n";
       print "Continue? ";
       chomp($ans = <STDIN>);
       $ans=lc($ans);
       if ( $ans =~ /y|yes/){
    4      $num=$dbh->do(qq/DELETE from teams WHERE name = ?/, undef,
           $name);
    5      print ($num > 1 ?"$num rows deleted.\n":"$num row deleted.\n");
       }
       else {
           die "You have not chosen to delete any entries. Good-bye.\n";
       }
        $sth->finish();
        $dbh->disconnect();
    
    (Output)
    Enter the team name you want to delete: Sunnyvale Seniors
    Number of rows to be deleted: 1
    Continue? y
    1 row deleted.
    
                                              
    

    Explanation

    1. The name of the team to be deleted is assigned to $team as input from the user. The SQL statement will query the database with the count function to find out how many rows were found matching the selected team name.

    2. The execute() method will send the query to the database, and the number of rows that matched the name of the team found will be returned.

    3. The results of the query are fetched. The user is given the opportunity to remove the entries found. If there aren't any matched teams, there is no point in continuing.

    4. The DBI do() method is used to prepare and execute the SQL DELETE statement.

    5. The number of rows deleted returned.

    Updating Entries

    To update or edit a database entry, we use the SQL UPDATE statement with the DBI do() method.

    Example 17.42.
       use DBI;
       my $driver="DBI:mysql";
       my $database="sample_db";
       my $user="root";
       my $password="quigley1";
       my $host="localhost";
    
       my $dbi=
    DBI->connect("$driver:database=$database;host=$host;user=$user;
    password=$password")or die "Can't connect: " . DBI->errstr;
    
       my $num_of_wins;
       my $num_of_losses;
       my $count;
    1  print "What is the name of the team to update? ";
       chomp($team_name=<STDIN>);
    
       # Show user the table before he tries to update it
    2  my $sth=$dbi->prepare(qq/SELECT * FROM teams
         WHERE name="$team_name"/) or die "Select failed: ". $DBI::errstr;
       $sth->execute() or die "Execute failed:".$DBI::errstr;
    3  while(($name, $wins, $losses) = $sth->fetchrow_array()){
    4    $count++;
         print "\nData for $team_name before update:\n"if $count == 1;
         print "\t\twins=$wins\n";
       print "\t\tlosses=$losses\n\n";
       }
    5  if ($count==0){ die "The team you entered doesn't exist.\n";}
    6  print "How many games has $team_name won since the last update?";
       chomp($num_of_wins=<STDIN>);
    7  print "How many games has $team_name lost since the last update? ";
       chomp($num_of_losses=<STDIN>);
    
    8  $dbi->do(qq/UPDATE teams SET wins=wins+$num_of_wins
         WHERE name = ? /, undef, "$team_name") or
         die "Can't update teams :". DBI->errstr;
    
    9  $dbi->do(qq/UPDATE teams SET losses=losses+$num_of_losses
         WHERE name = ? /, undef, "$team_name") or
         die "Can't update teams :". DBI->errstr;
    
       # Show the user the table after it is updated
       print "\nData for $team_name after update:\n";
    10 $sth=$dbi->prepare(qq/SELECT * FROM teams WHERE
       name="$team_name"/);
       $sth->execute();
       while(($name, $wins, $losses) = $sth->fetchrow_array()){
         print "\t\twins=$wins\n";
         print "\t\tlosses=$losses\n\n";
       }
    
       $sth->finish();
       $dbi->disconnect();
    
    (Output)
    What is the name of the team to update? Chico Hardhats
    Data for Chico Hardhats before update:
                    wins=15
                    losses=3
    How many games has Chico Hardhats won since the last update? 1
    How many games has Chico Hardhats lost since the last update? 2
    Data for Chico Hardhats after update:
                    wins=16
                    losses=5
    
                                              
    

    Explanation

    1. The user is asked to enter the name of the team in the teams table that he will edit.

    2. A SELECT statement is issued to retrieve all the data in the teams table.

    3. Before performing the update, the table will be displayed to see it in its current state.

    4. The counter will keep track of how many records were returned.

    5. If the count is zero, nothing was returned from the SELECT, and the program will die with an error message.

    6. The user is asked to enter the number of games that have been won since the last update occurred.

    7. And the user is asked how many games have been lost since the last update.

    8. The DBI do method is used to prepare and execute the SQL UPDATE statement. It returns the number of rows that were affected by the update. This statement will update the wins column in the teams table.

    9. This update is the same as the last one, except it increases the number of losses.

    10. After the database table has been updated, this SELECT statement is reissued to show the user the table after it was edited.

    Previous Page Next Page
  • 相关阅读:
    【杭电】[4857]逃生
    【杭电】[2647]Reward
    【杭电】[1285]确定比赛名次
    【杭电】[1251]统计难题
    OJ系统上线——OJ.BoilTask.com
    【郑轻】[1893]985的数学难题
    【郑轻】[1900]985的“树”难题
    【郑轻】[1898]985的数字难题
    HDU 1850———nim博弈
    HDU 2188------巴什博弈
  • 原文地址:https://www.cnblogs.com/jamespb/p/2160172.html
Copyright © 2011-2022 走看看