http://www.perlmonks.org?node_id=1003908

mrras25 has asked for the wisdom of the Perl Monks concerning the following question:

I have a sql query in perl that returns a column which could hold anything in it $#%@^"!_'/ and the string could be a long string and no telling where these specail characters will be placed in the string - I need to escape these characters before taking that string and inserting it back into the database.. </>

Please help - Thank you

Replies are listed 'Best First'.
Re: Need help escaping literal string
by davido (Cardinal) on Nov 15, 2012 at 01:32 UTC

      Thank you for the reply

      How exactly would I do it? Lets say I have a value of
      while(@values = $sth->fetchrow_array) { print "$values[8]\n"; }
      the return value of that is : /vol/enycmmcfl01b_ssd2_home_1b_a/CBirbigl$'s as you can see if I try and take that value and insert in to an insert statement to execute that through perl
      my $insert = "insert into dbtable (vol) values ('$values[8]')";
      the insert statement will now fail because it will look like
      insert into dbtable (vol) valuse ('/vol/enycmmcfl01b_ssd2_home_1b_a/CB +irbigl$'s')
      And well that wont work

        mrras25:

        That's why davido mentioned placeholders. It's something like:

        # Prepare a statement... my $sth = $dbh->prepare("insert into dbtable (vol) values (?)"); my $funky_string = "/vol/enycmmcfl01b_ssd2_home_1b_a/CBirbigl$'s"; $sth->execute($funky_string);

        This way, you don't have to worry about the odd characters inside your statement. Building your own statements like you were trying to do just leads to the difficulties you're experiencing. That's why placeholders were invented.

        ...roboticus

        When your only tool is a hammer, all problems look like your thumb.

        Typically it would look a little like this.

        my $insert = "insert into table (vol) values (?)"; $dbh->do($insert, $values[8]);

        Generally, the notion is that you never directly put variables into SQL statements.

Re: Need help escaping literal string
by MidLifeXis (Monsignor) on Nov 15, 2012 at 10:59 UTC

    Since nobody else has mentioned this yet -- if you assemble SQL in the manner you were originally attempting, you have a much higher probability of having problems once Bobby Tables starts working with you. Having a dropped table or proprietary data extracted can be an expensive lesson to learn.

    --MidLifeXis