[DB-SIG] format vs pyformat

Chris Cogdon chris@cogdon.org
Mon, 19 Aug 2002 14:52:46 -0700

On Monday 19 August 2002 14:23, Keating, Tim wrote:

> Am I missing something? Aren't you constructing a string and passing it=
> either way? Why would the database adapter care how it was formatted?

One isn't 'supposed to' construct the whole string yourself. If you pass=20
arguments to the execute method, the adaptor will do all the value quotin=
for you. For example:

cur.execute ( "select * from person where name ilike '%s'" % name )

wont always work, especially if 'name' contains characters special to the=
syntax. And:

cur.execute ( "select * from person where name ilike %r" % name )

won't work either, as the SQL quoting rules aren't the same as python's. =
I could do:

cur.execute ( "select * from person where name ilike '%s'" % dblib.quote(=

to explicitly call the quoting routine, but this is hardly an elegant=20
solution. The current protocol, to specify the quotable values as argumen=
to the execute method, is much neater:

cur.execute ( "select * from person where name ilike %s", name )

> In any case, dictionary-based formatting isn't nearly as ugly if you
> already have the data in a dictionary and don't have to construct an
> anonymous one to pass to the format operator. This might seem like a pa=
> but I suggest you look at the vars() built-in function and consider the
> possibilities . . .

It's rare that the values you want to pass to the formatter are handily i=
n a=20
dictionary already.

vars() is neat, but it means that you need to put all your values into lo=
variables before calling execute. Viz:

cur.execute ( "update person set thingy=3D%s", counter+1 )


newcounter =3D counter + 1
cur.execute ( "update person set thingy=3D%(newcounter)s", vars() )

In this example, 'format' parameter passing is by far shorter and neater.

   ("`-/")_.-'"``-._        Chris Cogdon <chris@cogdon.org>
    . . `; -._    )-;-,_`)
   (v_,)'  _  )`-.\  ``-'
  _.- _..-_/ / ((.'
((,.-'   ((,/   fL