Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3475

Re: strange use of %s

Date 2011-04-18 09:44 +0100
From Tim Golden <mail@timgolden.me.uk>
Subject Re: strange use of %s
References <4dabf65a$0$18250$4fafbaef@reader2.news.tin.it>
Newsgroups comp.lang.python
Message-ID <mailman.505.1303116284.9059.python-list@python.org> (permalink)

Show all headers | View raw


On 18/04/2011 09:29, Tracubik wrote:
> Hi all,
> i'm reading a python tutorial in Ubuntu's Full Circle Magazine and i've
> found this strange use of %s:
>
> sql = "SELECT pkid,name,source,servings FROM Recipes WHERE name like '%%%s%
> %'" %response
>
> response is a string. I've newbie in sql.
>
> why do the coder use %%%s%% instead of a simple %s?
> why he also use the ''?

Two parts to this answer.

The straightforward one: because the SQL string needs to end
up looking like this: "... WHERE name LIKE '%abcd%'" and
since it's being generated by Python's string substitution,
the surrounding percents need to be doubled up in the original
string to be left as single in the final string.

An alternative in a modern Python might be to use string formatting:
"... WHERE name LIKE '%{}%'".format (response)

HOWEVER... this is not the best way to introduce Python values into
a SQL string. It's better to use the db module's string substitution
flag (often ? or :field or, confusingly, %s). This is because the
approach above lends itself to what's called SQL injection.
Obligatory xkcd reference: http://xkcd.com/327/

The code would be better if written something like this:

   sql = "SELECT ... WHERE name LIKE '%' + ? + '%'"
   q = db.cursor ()
   q.execute (sql, [response])

(The details will vary according to the database being used etc.)

TJG

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

strange use of %s Tracubik <affdfsdfdsfsd@b.com> - 2011-04-18 08:29 +0000
  Re: strange use of %s Tim Golden <mail@timgolden.me.uk> - 2011-04-18 09:44 +0100
    Re: strange use of %s John Nagle <nagle@animats.com> - 2011-04-25 15:01 -0700
      Re: strange use of %s Chris Angelico <rosuav@gmail.com> - 2011-04-26 08:10 +1000
  Re: strange use of %s Chris Angelico <rosuav@gmail.com> - 2011-04-18 18:50 +1000
  Re: strange use of %s Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2011-04-18 22:22 -0700
  Re: strange use of %s Chris Angelico <rosuav@gmail.com> - 2011-04-19 15:31 +1000
  Re: strange use of %s Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2011-04-19 21:01 -0700

csiph-web