Home > Backend Development > Python Tutorial > Why Does My SQLite INSERT Statement Fail with \'Incorrect Number of Bindings\' for Long Strings?

Why Does My SQLite INSERT Statement Fail with \'Incorrect Number of Bindings\' for Long Strings?

Linda Hamilton
Release: 2024-11-30 10:23:15
Original
713 people have browsed it

Why Does My SQLite INSERT Statement Fail with

Incorrect Number of Bindings

When attempting to insert a string into a SQLite database using the code below, an error occurs indicating an incorrect number of bindings:

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

The error message appears when the string to be inserted is 74 characters long.

The Root of the Issue

The code attempts to pass a sequence of items to the execute() method as bind values. However, the bind value parameter requires a tuple, and the code neglects to provide the comma necessary to create a tuple.

cursor.execute('INSERT INTO images VALUES(?)', (img)) # Missing comma
Copy after login

The Fix

To resolve the issue, add a comma to the end of the bind value parameter to create a tuple:

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

Alternatively, you can use a list literal, which is also recognized as a valid sequence:

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

With either correction, the code will correctly insert the image path into the database without triggering the error message about an incorrect number of bindings.

The above is the detailed content of Why Does My SQLite INSERT Statement Fail with \'Incorrect Number of Bindings\' for Long Strings?. 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