Chinaunix首页 | 论坛 | 博客
  • 博客访问: 262842
  • 博文数量: 30
  • 博客积分: 4398
  • 博客等级: 中校
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-06 21:21
文章分类

全部博文(30)

文章存档

2013年(10)

2012年(1)

2011年(17)

2010年(2)

分类: Python/Ruby

2011-06-24 18:11:26

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

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