首页 > 解决方案 > 根据用户输入更新表

问题描述

我创建了一个包含以下详细信息的表:

myStr2 = "CREATE TABLE Lecturers (lec_no VARCHAR(3), name VARCHAR(30), email VARCHAR(30), PRIMARY KEY(lec_no))"

然后我创建了一个能够更新表的函数。

def update_lecturer(self, field_to_update, value_to_set, lec_no):
           self.field_to_update = field_to_update
           self.value_to_set = value_to_set
           self.lec_no = lec_no
           self.myCursor.execute("UPDATE Lecturers SET field_to_update = :field_to_update WHERE lec_no =:lec_no",{'field_to_update':self.field_to_update,'value_to_set':self.value_to_set,'lec_no':self.lec_no})

该表根据用户输入进行更新:

field_to_update = input("Field update:")
value_to_set = input("Value to set:")
lec_no = input("Lec_no:")

其中 field_to_update 可以是 name 或 email,value_to_set 可以是 name 的新值或 email 的新值。lec_no 是我们想要更改其详细信息的讲师的 ID。

但是,当我运行我的代码时,出现以下错误:

sqlite3.OperationalError: no such column: field_to_update

我知道我的表中没有 field_to_update 这样的列,但是如何根据用户输入设置要更新的列。

标签: python-3.xsqlitesql-update

解决方案


我在更新语句中连接变量 field_to_update 然后添加问号来表示其他两个变量并且它起作用了。这是我的代码:

def update_lecturer(self, field_to_update, value_to_set, lec_no):
           self.field_to_update = field_to_update
           self.value_to_set = value_to_set
           self.lec_no = lec_no
           self.myCursor.execute("UPDATE Lecturers SET "+self.field_to_update+" = (?) WHERE lec_no = (?)",(self.value_to_set,self.lec_no))       

           self.myConnection.commit() 

推荐阅读