Jun Jun - 1 year ago 55
Python Question

What am I doing wrong in my query?

So I have a table in my Customers.db file that looks like this:

enter image description here

I wanted to make a function which returns the "rows" which has the id equal to the user input. The Table is also called 'Customers and all the columns are type TEXT.

def run_query(db, query, args=NONE):
con = sqlite3.connect(db)
cur = con.cursor()
if args is None:
cur.execute(query, args)
data = cur.fetchall()
return data

def get_info_by_id(db, ide):
query = "SELECT * FROM Customers WHERE id = ?"
return run_query(db, query, ide)

When I ran this in the shell like this

get_info_by_id('Customers.db', '920')

I get the error "sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied."

Answer Source

The args argument of cur.execute needs to be an iterable so that they can be bound to multiple placeholders (?) if necessary. Therefore you should always be passing a list or tuple.

get_info_by_id('Customers.db', ['920'])

When you pass a string it gets treated as an iterable of single-character strings, hence it says there were 3 bindings (3 characters in '920').

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download