Something More Elegant

Tim Chase python.list at
Sat Jan 9 14:39:11 CET 2010

Victor Subervi wrote:
> Hi;
> The following code works fine. I would like you to suggest something more
> simple and elegant:
>       sql = 'select p.ID from %sPackages p join %sCategoriesPackages c where
> c.CategoryID=%s;' % (store, store, categoryID)
>       cursor.execute(sql)
>       tmp = [itm[0] for itm in cursor]
>       packageIDs = []
>       for t in tmp:
>         if t not in packageIDs:
>           packageIDs.append(t)

You mean like

   sql = "select distinct p.ID from ..." % (...)
   #             ^^^^^^^^
   package_ids = [row[0] for row in cursor.fetchall()]

It would also help if you didn't pass the categoryID as a 
string-formatted value, but as a proper parameter, something like

   sql = "... where c.categoryid=?" % (store, store)
   cursor.execute(sql, (category_id,))

This helps prevent SQL-injection attacks (assuming you have full 
control over the value of "store"...otherwise, as you've been 
advised, if the remote user has control over the value in 
"store", you're asking to be exploited).  You'd have to check the 
place-holder character for your particular back-end:

   >>> import <your database engine> as db
   >>> print db.paramstyle

should tell you whether to use "?", "%s", or some other notation.

More information about the Python-list mailing list