【问题标题】:Sqlalchemy sqlite "too many SQL variables"Sqlalchemy sqlite“SQL变量太多”
【发布时间】:2015-01-14 06:26:03
【问题描述】:

我有两个处于一对多关系的实体。在某些情况下,实体之一具有超过 999 个子实体。我想删除实体及其子实体,但遇到 sqlite 最大 sql 变量的问题:

connection.execute(child.delete().where(child.c.parent_id == parent_id))
connection.execute(parent.delete().where(parent.c.id == parent_id))

sqlalchemy.exc.OperationalError:
OperationalError: (OperationalError) too many SQL variables u'DELETE FROM child WHERE child.parent_id IN (?,?...

我发现 sqlite 中的 maxium sql 变量是 999,所以这就是我的问题所在。我在另一个问题中阅读了答案,这是一个建模问题 (https://stackoverflow.com/a/8433514/931325),但我不知道如何以不同的方式对数据建模。

我有什么办法来解决这个问题?

【问题讨论】:

  • 你的 SQL 引擎是什么? (mysql, sqlite, ...)
  • 它的 SQLite。我不认为这是其他引擎的问题。

标签: sqlite sqlalchemy


【解决方案1】:

尝试删除不同块中的行。您可以使用 limit(999),因为最大 SQLITE_LIMIT_VARIABLE_NUMBER 等于 999。这是您需要做的 pesudo

from sqlalchemy import func, in_

# getting the amount of total rows
stmt = select([func.count(child.c.parent_id).label('num_rows_childs')]).where(child.c.parent_id == parent_id)
number_of_rows = conn.execute(stmt).fetchall()

# Getting quotient and reminder of all rows on 999
# This gives you the number of times that delete() should run
# div_mod[0] is the quotient
# div_mod[1] is the reminder
div_mod = divmod(number_of_rows[0], 999)

for x in xrange(div_mod[0]):
    child.delete().where(child.c.parent_id.in_(select([child.c.parent_id]).where(child.c.parent_id == parent_id).limit(999).all()))
else:
    child.delete().where(child.c.parent_id.in_(select([child.c.parent_id]).where(child.c.parent_id == parent_id).limit(div_mod[1]).all()))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2021-04-02
    • 2019-10-05
    • 2019-06-05
    • 2019-05-07
    相关资源
    最近更新 更多