Paulina Paulina - 1 year ago 76
MySQL Question

Python/MySQL "Insert into" with variables

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)

Answer Source

You do it like this:

add_word = "INSERT INTO %s (name, surname) VALUES ('%s', '%s')"%('table_name','name','surname1')

and then you don't need data_word:

cursor.execute(add_word, params=None, multi=False)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download