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()
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()
Alternatively, we can use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
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!