QuoteSQL

Duncan Booth duncan.booth at invalid.invalid
Wed Sep 27 14:01:29 CEST 2006


Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote:

> I'm assuming you mean, how would you get from a Python expression to a
> MySQL clause that looks like
> 
>     name like "%\\\\%%"
> 
> (wildcard % followed by literal backslash \\ followed by literal
> percent \% followed by wildcard %.) That's easy:
> 
>     EscapeSQLWild(r"\%") => r"\\%"
>     SQLString(r"\\%") => r'"\\\\%"'
> 
> So the Python expression
> 
>     "name like %s" % SQLString("%" + EscapeSQLWild(r"\%") + "%")
> 
> gives you what you want.
> 
Deary me. Did you actually test out that bit of code before you posted it? 
No, I thought not. I even gave you a test harness to make it easy for you 
to check the quality of your code before posting.

All you had to do was to add another test:

    def test_escapebackslashwild2(self):
        self.cursor.execute(
            ("select name from pythontest where name like %s" %
            SQLString("%" + EscapeSQLWild(r"\%") + "%")))
        expected = (('x\\%x',),)
        self.assertEqual(expected, self.cursor.fetchall())

and the output is:
======================================================================
FAIL: test_escapebackslashwild2 (__main__.Tests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "mysqltest.py", line 111, in test_escapebackslashwild2
    self.assertEqual(expected, self.cursor.fetchall())
AssertionError: (('x\\%x',),) != (('x\\nx',), ('x\\%x',))

----------------------------------------------------------------------

as I said before, your escaping is too late and not enough. You've got a 
search for a literal backslash in there sure enough, but you haven't 
managed to escape the percent character.

Try again.



More information about the Python-list mailing list