python-3.x - 根据用户输入更新表
问题描述
我创建了一个包含以下详细信息的表:
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 这样的列,但是如何根据用户输入设置要更新的列。
解决方案
我在更新语句中连接变量 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()
推荐阅读
- jquery - CheckBox 在 ASP.NET MVC 中总是返回 null
- c# - .Net Webapi 不显示所需属性的错误消息
- css - 带有 CSS 的闪亮进度条
- nativescript - NativeScript 应用程序路由器错误。我的应用程序无法启动
- c# - Converting a string pulled from the internet into a DateTime
- android - Polidea RxAndroidBle 启用通知
- javascript - 使用 Vue.js 和 FirebaseUI,身份验证成功后如何存储 authResult 对象?
- jquery - 在 IE 中,输入换行符会导致
为 contentEditable 插入
- java - JavaFX折线图抛出异常
- python - ModuleNotFoundError:没有名为“加密”的模块错误