SQL Query via python

Jeff Elkins jeffelkins at earthlink.net
Sat May 21 09:40:39 EDT 2005


On Saturday 21 May 2005 04:56 am, Heiko Wundram wrote:
> Am Samstag, 21. Mai 2005 06:54 schrieb Sakesun Roykiattisak:
> > Try
> >
> > cursor.execute (
> > """
> >   SELECT name, month, day ,category, city FROM bday
> >   WHERE %s = %s
> > """
> >   %(arg1,arg2))
>
> *argh* You don't do any quoting of SQL-parameters, and that's more than
> bad! (leaves you up to the mercy of SQL-injection attacks, for example)
>
> What you basically want to have is something like the following:
>
> # Make sure arg1 is actually just characters.
> if not arg1.isalpha():
>     raise RuntimeError, "trying to do SQL-injection attack?!"
>
> # Now do query.
> cursor.execute("""
> SELECT name, month, day, category, city FROM body
> WHERE %s = %%s
> """ % (arg1,),
> (arg2,))
>
> See how I didn't just use arg1 to paste it in the query string, but checked
> it before trying the query to consist only of characters. You'd have to
> adjust this accordingly for field-names you use (maybe you use underscores,
> etc.). But, be sure that arg1 contains no ";"!
>
> HTH!

Hey, I could barely spell SQL yesterday...:)

I really appreciate the pointers!

Jeff







More information about the Python-list mailing list