不幸的是我没有找到问题的答案,所以我在这里试试。我认为这很容易,但我不能做对。既然这是我的第一个问题,我希望我做得对。
我使用Python 3.5和MySql。我使用MySql连接器模块并安装并激活了mysql-server。我想用来自用户输入的变量动态生成查询。这是一个简单的程序,我想让用户编辑表条目。它适用于所有情况,例如:
SET title =%s
或WHERE标题=%s
但是,当我想将列名title
设为变量时,它会出错(此处('标题')广告('所有者')均来自用户输入)。执行代码块底部的第二个c.execute()
块时发送错误:
> mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('title') = ('owner') WHERE id = ('4')' at line 1
"标题"是表的列名。所以我希望用户选择他想要更改的列,而不仅仅是值。
我只是没有得到第一个变量的格式。请参阅下面的代码片段,希望它更清晰(最后3行是这里的主要焦点:
id_edit = input("Which Application do you want to change? (give Id): ")
id_edit = str(id_edit)
# field_edit is the word "Company" or "Title" for selecting the right column
old_field = input('Which field of Application "%s" do you want to change?: ' % (id_edit))
old_field = old_field.lower()
# new_field: Here the user gives the Input How he wants to name the Field instead
new_field = input('What should be the new value for the id "%s"?: ' % (old_field))
new_field = new_field.lower()
if old_field in table_names():
# this works fine:
c.execute("UPDATE applications SET title = (%s) WHERE id = (%s)", (new_field, id_edit))
# this is how I want it to work:
c.execute("UPDATE applications SET (%s) = (%s) WHERE id = (%s)", (old_field, new_field, id_edit))
conn.commit()
提前谢谢!