Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Perl编写SQL文件_Sql_Perl - Fatal编程技术网

从Perl编写SQL文件

从Perl编写SQL文件,sql,perl,Sql,Perl,我是Perl的新手,有PHP编码经验,我编写了这个Perl脚本来读取一个没有EOL字符的相当大的数据文件,并用INSERT语句创建一个SQL文件。我的问题是,在源文件中有“特殊字符”(例如单引号),由于这些字符,我最终得到了无效的SQL查询 我的问题是:在构建SQL查询之前,是否有任何方法可以转义数据 下面是Perl脚本: #! /usr/bin/perl use strict; use warnings; my $filename = "foo.dat"; my $buf = ""; op

我是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);
#/usr/bin/perl
严格使用;
使用警告;
我的$filename=“foo.dat”;
我的$buf=“”;
打开(MYFILE,'>data.sql');

open(my$fh,“您唯一需要担心的字符是单引号。您可以将其替换为:

$aa =~ s/'/''/g;
更常见的方法是要求数据库库进行编码,如:

$dbh->quote($thestring);
但是,由于您正在写入文件,因此似乎没有数据库库。

如果您希望保留文件的内容,直接写入数据库,然后对文件执行数据库转储可能会更容易(也更安全)。