SQL Query via python

Heiko Wundram modelnine at ceosg.de
Sat May 21 04:56:33 EDT 2005


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!

-- 
--- Heiko.
  see you at: http://www.stud.mh-hannover.de/~hwundram/wordpress/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050521/05ea5a92/attachment.sig>


More information about the Python-list mailing list