Python/MySQL “Insert into” with variables

被刻印的时光 ゝ 提交于 2019-12-12 03:44:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!