[DB-SIG] SQL string escape function

Kevin Cole kjcole@gri.gallaudet.edu
Tue, 24 Jul 2001 08:01:53 -0400 (EDT)


There might be a nice SQL-ish way to do it, but another way to do it is
to pass all your strings through Python's regular expression module
"re".  The following takes a list that may or may not contain string
elements and replaces any of the special characters between the
single quotes in the re..compile() with the same string surrounded by
double quote marks.  (It first checks to see if the a is a string, and
if the function was called with "lout" as the format argument.)
-----------------------------------------------------------------------------
  import types
  import re                                           # Reg exp module
  quotable = re.compile(r'([/|&{}#@^~\\]+)')          # Lout special chars

  def escape(row,format):
    if format == "lout":                              # Format for Lout?
      for col in range(len(row)):                     # Check each element
        if type(row[col]) == types.StringType:        # Is it a string?
          row[col] = quotable.sub(r'"\1"',row[col])   # Substitute
-----------------------------------------------------------------------------

For documentation on use, see the Regular Expression HOWTO at:

       http://py-howto.sourceforge.net/

Hope this helps you...

On Mon, 23 Jul 2001 moored@reed.edu wrote:

>  Forgive my ignorance and inability to find a manual: Is there a function
> that will escape special characters from a string such that it can be
> included in a SQL statement? I'm looking for something like the php
> AddSlashes().
>
> -------===Dustin Moore===---------
>
>
>
> _______________________________________________
> DB-SIG maillist  -  DB-SIG@python.org
> http://mail.python.org/mailman/listinfo/db-sig
>

-- 
 Kevin Cole, RHCE, Linux Admin  |  E-mail:  kjcole@gri.gallaudet.edu
 Gallaudet Research Institute   |  WWW:     http://gri.gallaudet.edu/~kjcole/
 Hall Memorial Bldg  S-419      |  Voice:   (202) 651-5135
 Washington, D.C.  20002-3695   |  FAX:     (202) 651-5746