[Tutor] SQLite LIKE question

Steve Willoughby steve at alchemy.com
Fri Apr 11 12:22:25 CEST 2008


Simone wrote:
> In Python the symbol '%' in a string is a special char: you use it, for 
> instance, to place a variable inside a string.

For completeness, it's worth mentioning in passing that % is only
special when you're doing string formatting.  It's not otherwise
special in strings.

> However, as Alan said, the method with the question mark to construct 
> the query is more safe than this.

Way way way way way safer.  In fact, forget that you can even
use string formatting to put values into SQL queries.  At all.
Unless you know precisely what you're doing.  And even then
don't do it.  Really.  That way lies madness.  And more,
larger, and more disastrous SQL database problems than possibly
any other error.

If your library supports specifying a SQL query string using
placeholders (and supplying those values in a tuple which
the database module will paste in on its own), it will know
to properly quote or escape special characters in those
data values.

Some modules use ? as the place holder, others use %s (even
for numeric values, interestingly enough).  Check with
your documentation.


--steve



More information about the Tutor mailing list