开发者

Writing a SQL file from Perl

I am a complete newbie to Perl, with 开发者_如何学编程PHP coding experience and I put together this Perl script to read a fairly big datafile with no EOL characters and create a SQL file with INSERT statements. My problem is that in the source file there are "special chars" (single quote, for example) and because of those chars I end up with invalid SQL queries.

My question: is there any way to escape data before building the SQL query?

Here's the Perl script:

#! /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);


The only character you'd have to worry about is the single quote. You can replace it like:

$aa =~ s/'/''/g;

A more usual way is to ask the database library to do the encoding, like:

$dbh->quote($thestring);

But since you're writing to a file, you don't seem to have a database library around.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜