设为首页 收藏本站
查看: 782|回复: 0

[经验分享] Perl working with mysql

[复制链接]

尚未签到

发表于 2015-12-27 12:27:03 | 显示全部楼层 |阅读模式








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, 3The 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.



Code View:

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







  • 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.




  • 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.




  • 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.




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




  • 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.



Code View:

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







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




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




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




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




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




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




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




  • 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.




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




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









运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-156934-1-1.html 上篇帖子: perl--单元测试 下篇帖子: 小时代5-perl上下文介绍
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表