【问题标题】:sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 suppliedsqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用 2,并且提供了 1
【发布时间】:2021-10-28 16:31:38
【问题描述】:

我想在表中插入“file_number”和“file_id”列。 file_number 应该是自增的,因为它是 PRIMARY KEY。我认为问题出在 cur.execute(_insert, [file_id]) 行上。 _insert 是 SQL 语句,方括号之间的项目是要插入的字符串。我认为这会引发错误,因为我没有在这些方括号中包含“file_number”。但是我应该如何包含要自行增加的东西呢?我还是不明白。提前致谢!

class Image:
    _name = "image"
    table = f"""
    CREATE TABLE IF NOT EXISTS "{_name}"
    (   "file_number" INTEGER PRIMARY KEY,
        "file_id" TEXT
    );
    """

    def __init__(self, db: SQL):
        self.db = db

    def add(self, file_id):
        """Agrega una file_id a la base de datos"""
        _insert = f"""INSERT or IGNORE INTO {self._name}(file_number, file_id)
        VALUES(?,?)"""
        cur = self.db.cursor()
        cur.execute(_insert, [file_id])
        self.db.commit()
        cur.close()

【问题讨论】:

    标签: python sqlite


    【解决方案1】:

    来自documentation for the Autoincrement value

    在 INSERT 中,如果 ROWID 或 INTEGER PRIMARY KEY 列没有显式地给定一个值,那么它将用一个未使用的整数自动填充,通常比当前使用的最大 ROWID 多一个。无论是否使用 AUTOINCREMENT 关键字都是如此。

    换句话说,您根本不需要指定自动增量值,它会在插入时被赋予一个未使用的整数,然后绑定的数量和您传入的参数数量将匹配:

    _insert = f"""INSERT or IGNORE INTO {self._name}(file_id)
            VALUES(?)"""
    // ...
    cur.execute(_insert, [file_id])
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2020-09-10
      • 2013-05-27
      • 2020-10-15
      • 2016-01-21
      相关资源
      最近更新 更多