"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Resolve Parameter Substitution Issues in SQLite When Using Sequences vs. Strings?

How to Resolve Parameter Substitution Issues in SQLite When Using Sequences vs. Strings?

Published on 2024-11-08
Browse:208

How to Resolve Parameter Substitution Issues in SQLite When Using Sequences vs. Strings?

Troubleshooting Parameter Substitution Issues in SQLite

Encountering issues when utilizing parameter substitution in SQLite3 with Python? Here's an in-depth investigation and a resolution.

In an attempt to prevent SQL injections, parameter substitution using '?' is advisable. However, an error may arise when utilizing this approach. For instance, with the following code:

for item in self.inventory_names:
    self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
    self.cursor.close()

The error "sqlite3.ProgrammingError: Incorrect number of bindings supplied" occurs, indicating that the statement specifies one binding, whereas eight are provided. This issue stems from the initial creation of the database table. The module responsible for database creation contains eight bindings, which leads to the mismatch.

cursor.execute("""CREATE TABLE Equipment 
    (id INTEGER PRIMARY KEY, 
    name TEXT,
    price INTEGER, 
    weight REAL, 
    info TEXT, 
    ammo_cap INTEGER, 
    availability_west TEXT,
    availability_east TEXT)""")

Ironically, substituting '?' with a less secure '%s' resolves the problem:

for item in self.inventory_names:
    self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
    self.cursor.close()

The reason behind this paradox lies in the way Cursor.execute() accepts its second parameter. Instead of a single string, it expects a sequence, but you are passing a string of length eight.

To rectify this issue, adjust the code to the following:

self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item])

This modification ensures that the parameter substitution works as intended. Always ensure that the second parameter passed to Cursor.execute() corresponds to the specified number of bindings in the SQL statement.

Release Statement This article is reprinted at: 1729322897 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3