[DB-SIG] Mysqldb python variable in request

Andy Dustman andy at dustman.net
Sat Jan 24 11:43:33 EST 2004


On Thu, 2004-01-22 at 04:38, samira M'Bata wrote:

> target= 'DataType'
> constraint= 'Location'
> #DataType and Location are two columns of my Table
> constraint_value= 'stuttgart'
> cursor.execute(""" select %s from Xml2Mysql where %s=%s """,(target, 
> constraint, constraint_value))
> 
> I think the problem comes from the fact that my columns names are not as a 
> string type defined.
> 
> Should I change something in my table definition?

Simply put, table column names cannot be passed as parameters using the
DB-API; this is not particularly a MySQLdb issue. Your code should look
something like this.

target= 'DataType'
constraint= 'Location'
#DataType and Location are two columns of my Table
# note doubled % for parameter placeholder
base_query = """ select %s from Xml2Mysql where %s=%%s """
real_query = base_query % (target, constraint)
constraint_value= 'stuttgart'
cursor.execute(real_query, (constraint_value,))

As someone else has pointed out, if you are taking table or column names
from user-supplied data, you'd better check them very, very carefully. A
malicious user could execute arbitrary SQL code this way.
-- 
Andy Dustman         PGP: 0x930B8AB6
    @       .net     http://dustman.net/andy
Freedom isn't free. It's sold to the highest bidder.



More information about the DB-SIG mailing list