Skip to content Skip to sidebar Skip to footer

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 na

Solution 1:

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)

Solution 2:

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)

Post a Comment for "Python/MySQL "Insert Into" With Variables"