有关Perl操作数据库对SQL语句的过滤问题

发布时间:2020-12-11编辑:脚本学堂
使用perl的DBI模块操作数据库很便捷。一般简单的操作可以写成:#!/bin/perl use strict; use warnings; use DBI;

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

复制代码 代码如下:

#!/bin/perl

use strict;
use warnings;
use DBI;

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

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

$sth->execute();

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

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

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

复制代码 代码如下:

#!/bin/perl

use strict;
use warnings;
use DBI;

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

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

for my $field (@arr) {
$sth->execute($field);
}

$sth->execute();

如此,不但解决了Perl代码对SQL语句的过滤的问题,同时代码也更工整,且优化了查询。