Home > Backend Development > Python Tutorial > Why Does SQLite3 Throw a \'Mismatched Bind Value Count\' Error When Inserting Data?

Why Does SQLite3 Throw a \'Mismatched Bind Value Count\' Error When Inserting Data?

Linda Hamilton
Release: 2024-11-29 01:15:13
Original
212 people have browsed it

Why Does SQLite3 Throw a

SQLite3 Error: Mismatched Bind Value Count

When inserting values into a SQLite3 database using the cursor.execute() method, it's crucial to ensure that the number of bind values provided matches the number specified in the SQL statement's parameters. Otherwise, you may encounter an error similar to "Incorrect number of bindings supplied."

Consider the following code snippet:

def insert(array):
    connection=sqlite3.connect('images.db')
    cursor=connection.cursor()
    cnt=0
    while cnt != len(array):
            img = array[cnt]
            print(array[cnt])
            cursor.execute('INSERT INTO images VALUES(?)', (img))
            cnt+= 1
    connection.commit()
    connection.close()
Copy after login

When trying to insert a string of length 74, this code throws the aforementioned error. The reason is that the cursor.execute() method is expecting a sequence of bind values, while (img) is just an expression.

To fix this, we need to convert (img) into a tuple or list by adding a comma. Here's the corrected code:

def insert(array):
    connection=sqlite3.connect('images.db')
    cursor=connection.cursor()
    cnt=0
    while cnt != len(array):
            img = array[cnt]
            print(array[cnt])
            cursor.execute('INSERT INTO images VALUES(?)', (img,))  # Add a comma
            cnt+= 1
    connection.commit()
    connection.close()
Copy after login

Alternatively, we can use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])
Copy after login

The above is the detailed content of Why Does SQLite3 Throw a \'Mismatched Bind Value Count\' Error When Inserting Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template