【问题标题】:How can I search in a database using an integer id variable?如何使用整数 id 变量在数据库中搜索?
【发布时间】:2021-03-17 21:51:12
【问题描述】:

我正在开发一个 CRUD 图形界面。

def crudRead():
myConex=sqlite3.connect("Users")
myCursor=myConex.cursor()
myCursor.execute("SELECT*FROM USER_DATA WHERE ID="+id_number.get())
theUser=myCursor.fetchall()
for user in theUser:
    id_number.set(usuario[0])
    username.set(usuario[1])
    password.set(usuario[2])
    biographyText.insert(1.0, usuario[3])

myConex.commit()

错误: myCursor.execute("SELECT*FROM USER_DATA WHERE ID="+id_number.get())

TypeError: 只能将 str(不是“int”)连接到 str


如何在不出现该错误的情况下按 id 进行搜索? 我尝试设置 id_number.get() 并没有返回任何错误,但程序无法正常工作,因为数据库中的 ID 列具有整数值。

【问题讨论】:

  • 请参阅documentation,了解如何为 SQL 查询提供参数。

标签: python python-3.x database sqlite tkinter


【解决方案1】:

使用占位符:

myCursor.execute("SELECT * FROM USER_DATA WHERE ID=?", (id_number.get(),))

【讨论】:

  • 这也比构建查询字符串更安全。
【解决方案2】:

也许使用 f 个字符串会有所帮助。

myCursor.execute(f'SELECT*FROM USER_DATA WHERE ID={id_number.get()}')

【讨论】:

  • 像这样构建查询存在 sql 注入风险,这是当今系统被黑客入侵的主要方式之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 2016-09-10
  • 1970-01-01
  • 2013-03-05
  • 2016-07-19
相关资源
最近更新 更多