【发布时间】:2010-12-04 19:37:46
【问题描述】:
我是 Perl 的新手,具有 PHP 编码经验,我整理了这个 Perl 脚本来读取一个没有 EOL 字符的相当大的数据文件,并创建一个带有 INSERT 语句的 SQL 文件。我的问题是在源文件中有“特殊字符”(例如单引号),并且由于这些字符,我最终得到了无效的 SQL 查询。
我的问题:在构建 SQL 查询之前有什么方法可以转义数据?
这是 Perl 脚本:
#! /usr/bin/perl
use strict;
use warnings;
my $filename = "foo.dat";
my $buf = "";
open (MYFILE, '>data.sql');
open(my $fh, "<", $filename) or die $!;
while(read($fh, $buf, 80)) {
if ( defined $buf && length $buf > 2 ) {
my $aa = substr $buf, 0, 2;
my $bb = substr $buf, 2, 1;
my $cc = substr $buf, 3;
print MYFILE "INSERT INTO foo (aa, bb, cc) VALUES ('".$aa."', '".$bb."', '".$cc."')\n";
}
}
close (MYFILE);
【问题讨论】:
-
直接写入数据库可能更容易(也更安全),然后如果您希望保留其内容,则将数据库转储到文件。