Unsupported operand types in if/else list comprehension

Diez B. Roggisch deets at nospam.web.de
Sun Apr 12 10:00:04 CEST 2009

Mike H schrieb:
> Sigh. One more. And again, thank you for all of the help.
> I realized that the last version that I posted took care of an SQL
> injection problem for the values, but not for the fields. So, I went
> ahead and modified the code:
> def new_insert_cmd(myTable, myFields, myValues):
>     """Imports given fields and values into a given table, returns the
> Autoincrement value."""
>     SQLcmd="INSERT INTO " + myTable + " ( " +
> create_input_string(myFields) + " ) VALUES ( " \
>             + create_input_string(myValues) +" );"
>     allArguments=myFields+myValues
>     cursor.execute(SQLcmd, (allArguments))
> create_input_strings() is just a function that creates the necessary
> number of %s's for a given list (and which I'm sure there's a faster
> way to code):
> def create_input_string(myList):
>     sOut=""
>     for var in myList:
>         sOut=sOut+"%s, "
>     return sOut[:-2]
> However, now the cursor.execute statement won't work. I've looked at
> the content of SQLcmd and the values of allArguments and they seem
> fine.
> I've even tried running this at the IDLE command line:
> cursor.execute("INSERT INTO plan (%s, %s, %s) VALUES (%s, %s, %s);",
> (["name", "fileno", "size", "Test", "AAA-000", 7])) and I get this
> error:
> File "C:\Python25\lib\site-packages\MySQLdb\cursors.py", line 166, in execute
>     self.errorhandler(self, exc, value)
>   File "C:\Python25\lib\site-packages\MySQLdb\connections.py", line
> 35, in defaulterrorhandler
>     raise errorclass, errorvalue
> ProgrammingError: (1064, "You have an error in your SQL syntax; check
> the manual that corresponds to your MySQL server version for the right
> syntax to use near ''name', 'fileno', 'size') VALUES ('Test',
> 'AAA-000', 7)' at line 1")
> Can I not use the cursor.execute command to pass variables that aren't
> immediately next to each other? If so, is there a better way to go
> about solving this problem?

The escaping mechanism is only working (and supposedly so) for *values*, 
not for creating SQL. To prevent SQL-injection don't allow dynamic 
content in there (there shouldn't be any need anyway, because your 
datamodel isn't changing due to user-input)


More information about the Python-list mailing list