I am having trouble finding the documentation to be able to add non-SQL variables to a SQL statement The official docs don't go into that at http://dev.mysql.com/doc/refman/5.0/en/user-variables.html.

How would I do the following in python and valid SQL?

id, provider_id, title = row[0], row[2], row[4]
cursor.execute("INSERT INTO vendor_id VALUES (%s,%s,%s);"%(id, provider_id, title))
有帮助吗?

解决方案

You're on the right track but it should look like this.

id, provider_id, title = row[0], row[2], row[4]
cursor.execute("INSERT INTO vendor_id VALUES (%s, %s, %s)", id, provider_id, title)

The python SQL database API automatically disables and ask for a reformation of escaping and quoting of variables. String formatting operators are unnecessary and in this case do not do any formatting of variable quoting. You can format the final array of variables any way you like, just do not use the % operator like you use. If I am correct, the reason for this is that the variables are bound, and not formatted into the text, so that an injection cannot occur

cursor.execute("INSERT INTO vendor_id VALUES (%s, %s, %s)", (id, provider_id, title))
cursor.execute("INSERT INTO vendor_id VALUES (?, ?, ?)", (id, provider_id, title))

should work too.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top