-1

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)
    else:
        cur.execute(query, args)
    data = cur.fetchall()
    cur.close()
    con.close()
    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."

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jun
  • 91
  • 1
  • 10

2 Answers2

1

You need to update your run_query function as:

def run_query(db, query, *args):
    #                     ^ *args here for variable number of arguments
    #                        It will read additional arguments as tuples
    ..
    cur.execute(query, args)   # No need of if-else now
    ..                         # It expects arguments to be in tuple format

For more information related to *args, take a look at: What does asterisk * mean in Python?

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

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').

Alex Hall
  • 34,833
  • 5
  • 57
  • 89