Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2773324
  • 博文数量: 154
  • 博客积分: 7136
  • 博客等级: 准将
  • 技术积分: 1428
  • 用 户 组: 管理员
  • 注册时间: 2010-02-21 11:26
文章分类

全部博文(154)

文章存档

2016年(2)

2014年(2)

2013年(4)

2012年(16)

2011年(51)

2010年(68)

2009年(3)

2006年(3)

2005年(5)

分类:

2011-08-12 14:29:31

使用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语句的过滤的问题,同时代码也更工整,优化了查询。

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