[DB-SIG] warning problem

Chris Cogdon chris@cogdon.org
Fri, 16 Aug 2002 10:22:24 -0700


On Friday 16 August 2002 06:39, Watt III, Glenn wrote:

> if query['accept'].value =3D=3D "Yes":
>     update =3D 'update newpapers set firstname=3D"' + query["name"].val=
ue +
> '"'
>     update =3D update + ", title=3D'accepted'"
>     if query.has_key("emial"):
>         update =3D update + ', email=3D"'+query["email"].value+'"'
>     if query.has_key("web"):
>         update =3D update + ', web=3D"'+query["web"].value+'"'
>     if query.has_key("location"):
>         update =3D update + ', city=3D"'+query["location"].value+'"'
>     if query.has_key("papertitle"):
>         update =3D update + ', papertitle=3D"'+query["papertitle"].valu=
e+'"'
[... and so on...]

I know that this doesnt solve your immediate problem, but there is a 'sty=
le'=20
issue here that might bite you if you're not careful.

You're relying on all your input strings (eg, query["name"]) to not have =
any=20
special characters in them. For example, if that value contained a quote=20
character, you'll get a mysql errror.

The MySQLdb library contains an automatic quoting system, if you use it=20
properly, like this:

cursor.execute ( "update newpapers set firstname=3D%s, title=3D'accepted'=
 ...and=20
so on", query["name"], andotherparams )

The library will automatically figure out the type of your parameters, an=
d=20
quote them accordingly.

The above is called the 'format' parameter method. MySQLdb also supports=20
'pyformat', which can work like this:

cursor.execute ( "update newpapers set firstname=3D%(name)s, title=3D'acc=
epted'=20
=2E..and so on", query )

notice how the %(name)s will automatically pull out the proper value from=
 a=20
dictionary, just like the % operator in python, but /dont/ actually use %=
,=20
because then you wont get the automatic quoting.

Hope that's useful.

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