问题
I have a problem with inserting new rows to the MySQL table. The name of the table will change, so it must be a variable and with that I have the most trouble. How can I change name of the table "second" with variable? Any idea?
add_word = ("INSERT INTO second "
"(name, surname) "
"VALUES (%s, %s)")
data_word = (name1, surname1)
cursor.execute(add_word, data_word)
回答1:
You do it like this:
add_word = ("INSERT INTO {table} "
"(name, surname) "
"VALUES (%s, %s)")
atable = 'second'
data_word = (name1, surname1)
cursor.execute(add_word.format(table=atable), data_word)
回答2:
You are not going to be able to have the table name be data. You will have to put it in the sql statement. Maybe like this:
add_word = ("INSERT INTO {table} "
"(name, surname) "
"VALUES (%s, %s)")
table1 = 'second'
data_word = (name1, surname1)
cursor.execute(add_word.format(table=table1), data_word)
来源:https://stackoverflow.com/questions/37757747/python-mysql-insert-into-with-variables