Another Little MySQL Problem

John Nagle nagle at animats.com
Wed May 26 18:30:16 EDT 2010


Alister wrote:
> I think you should probably also write your execute differently:
> 
>>>>     clientCursor.execute('select ID from %s' , (personalDataTable,))
> 
> this ensures the parameters are correctly escaped to prevent mysql 
> injection attacks,the "," after personalDataTable is necessary to ensure 
> the parameter is passed as a tuple

    Actually, no.  The names of tables are not quoted in SQL.
One writes

	SELECT ID FROM mytable;

not

	SELECT ID FROM "mytable";

so you don't want to run table names through the quoting and escaping function.
If the table name is a variable, you need to be very careful about where it
comes from.

On the other hand, if you're specifying a data value, a field that's normally
quoted, as in

	SELECT ID from mytable WHERE mykey="foo";

you write

	cursor.execute("SELECT ID FROM mytable WHERE mykey=%s", (mykeyval,))

to get proper escaping.  Don't put quote marks around the %s; MySQLdb does that.

    Also, if you're selecting every entry in a database, without a
WHERE or ORDER BY clause, you will get the entries in more or less random
order.

					John Nagle



More information about the Python-list mailing list