SQL Query via python

Austyn Bontrager austynjay at yahoo.com
Mon May 23 12:12:31 EDT 2005


How about:

cursor.execute("""
	SELECT name, month, day ,category, city FROM bday
	WHERE %(col_name)s = %%s
	""" % dict(col_name=arg1),
	(arg2)
	)

The "%(col_name)s" will be replaced by normal Python string 
substitution, while the "%%s" will be quoted by the db module.

Watch out for SQL injection in arg1, though! Maybe check beforehand that 
it is a string containing only word characters...

Jeff Elkins wrote:
> I'm attempting to pass an SQL query via the console:
> 
> $ ./getbd month 05
> 
> The arguments get seem to passed correctly (via print statements) and then:
> 
>     cursor.execute ("""
>                      SELECT name, month, day ,category, city FROM bday
>                      WHERE %s = %s
>                    """,(arg1,arg2))
> 
> No results. However, if I hardcode the WHERE argument with a field name:
> 
>  cursor.execute ("""
>                      SELECT name, month, day ,category, city FROM bday
>                      WHERE month = %s
>                    """,(arg2))
> 
> It works.
> 
> How can I code the left side of the WHERE clause so I can pass an arbitrary 
> field name to search on?
> 
> 
> Thanks,
> 
> Jeff Elkins
> 
> 



More information about the Python-list mailing list