Chinaunix首页 | 论坛 | 博客
  • 博客访问: 34361
  • 博文数量: 9
  • 博客积分: 156
  • 博客等级: 入伍新兵
  • 技术积分: 60
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-22 16:36
文章分类
文章存档

2014年(1)

2012年(3)

2011年(5)

我的朋友
最近访客

分类:

2012-01-19 00:11:36

使用DBI操作数据库很便捷。一般简单的操作我们可以写成:

  1. use strict;
  2. use warnings;
  3. use DBI;

  4. my @arr=qw('xx' 'yy' 'zz');
  5. my $dbh=DBI->connect(...) or die 'unable to connect to database!';

  6. for my $field (@arr) {
  7. my $sql=qq{select from sometable where field=$field};
  8. my $sth=$dbh->prepare($sql);
  9. sth->execute();
  10. }

  11. $sth->execute();
但这里有时会遇到的一个问题就是Perl会解析SQL语句里标量的字符串,比如上面的标量$field,这样就会造成程序错误或是中断退出。

因为这里用的是 qq,相当于双引号,是允许它里面的内容进行转义的,所以会出现这样的问题。但如果用单引号的话,$field就不会被正常解析。

看了《Perl高效编程》第12章的106条,使用占位符的方法解决了这个问题,上面的代码可以写成:

  1. use strict;
  2. use warnings;
  3. use DBI;

  4. my @arr=qw('xx' 'yy' 'zz');
  5. my $dbh=DBI->connect(...) or die 'unable to connect to database!';

  6. my $sth=$dbh->prepare('select from sometable where field=?');

  7. for my $field (@arr) {
  8. $sth->execute($field);
  9. }

  10. $sth->execute();
这样不但解决了Perl代码对SQL语句的过滤的问题,同时代码也更工整,优化了查询。

阅读(1201) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~