Passing a column name in a SELECT statement in Python

You cannot use SQL parameters to interpolate column names. You’ll have to use classic string formatting for those parts. That’s the point of SQL parameters; they quote values so they cannot possibly be interpreted as SQL statements or object names.

The following, using string formatting for the column name works, but be 100% certain that the filters[0] value doesn’t come from user input:

cursor.execute("SELECT * FROM PacketManager WHERE {} = ?".format(filters[0]), (parameters[0],))

You probably want to validate the column name against a set of permissible column names, to ensure no injection can take place.

Leave a Comment