【问题标题】:Updating an SQL table while searching another SQL table在搜索另一个 SQL 表时更新一个 SQL 表
【发布时间】:2018-03-23 19:10:55
【问题描述】:

我有一个包含 3 个表的 SQL 数据库“Garage.db”: 客户、汽车和 MOT

当有人输入 Car 表中的注册时,我想更新 MOT 表中的 BookedMOT 字段。有人可以帮我处理可以执行此操作的 SQL 查询吗,谢谢。

我正在使用 tkinter 在 python 3.6 中对此进行编码。这是我的尝试,

    def Booked(self):
        date = Date.get()
        month = Month.get()
        year = Year.get()
        BookedMOT = (date + '/' + month + '/' + year)
        Registration = self.RegistrationEnt.get()
        with sqlite3.connect('Garage.db') as db:
            cursor = db.cursor()

        add_date = ('UPDATE MOT SET MOT.BookedMOT = ? FROM Car WHERE Car.Registration = ?')
        cursor.execute(add_date,[(BookedMOT), (Registration)])
        db.commit()

【问题讨论】:

  • 您遇到错误了吗?
  • cursor.execute(add_date,[(BookedMOT), (Registration)]) sqlite3.OperationalError: near ".": 语法错误
  • 更新不处理多个表。你在概念上想在这里做什么?您不能使用 Car 表上的约束从 MOT 表中指定一行。也许你想要这样的东西? stackoverflow.com/questions/329197/…
  • 我在 Car 表中没有 BookedMOT,所以我不确定。我对编码比较陌生,但我正在考虑使用 JOIN?
  • 向我们展示 SQL 表的定义,并解释一下它们背后的一些原因,特别是它们之间的关系。

标签: python sql python-3.x sqlite


【解决方案1】:

(这解决了我在意识到 SQL 看起来不正确之前就注意到的一些 Python 问题,这可能应该先修复)

试试这个:

with sqlite3.connect('Garage.db') as db:
    db.execute(add_date, (BookedMOT, Registration))

一般来说,当您说with ... as x: 时,您可能应该在with 块内使用x。块完成后,它会自动提交,之后尝试使用dbcursor 可能是不正确的。 with 也意味着您不再需要db.commit()

sqlite3 connection objects (db in this case) have an execute method:

这是一个非标准的快捷方式,它通过调用 cursor() 方法创建一个游标对象,使用给定的参数调用游标的 execute() 方法,并返回游标。

最后,您可以删除一些多余的括号。

【讨论】:

  • 我仍然得到这个错误,db.execute(add_date, (BookedMOT, Registration))sqlite3.OperationalError: near ".": syntax error –
猜你喜欢
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多