Home > other >  For loop SQLite SELECT statement
For loop SQLite SELECT statement

Time:02-26

Is this possible?

booking_details = []
for_quicksort = [1, 5, 9, 11, 19]


for i in range(len(for_quicksort)):
    fetch_booking_details = cursor.execute("SELECT * FROM booking WHERE customer_id=?", (for_quicksort(i)))
    booking_details.append(fetch_booking_details)

TypeError: 'list' object is not callable

CodePudding user response:

for_quicksort(i)

You're just using the wrong type of brackets, as far as I can tell. To index a list, use square brackets []. Round brackets () are used to call a function (and for enclosing data in some data structures, like tuples).

Corrected:

for_quicksort[i]

CodePudding user response:

Iterate over the list (for_quicksort). No need for explicit indexing.

booking_details = []
for_quicksort = [1, 5, 9, 11, 19]


for cust_id in for_quicksort:
    cursor.execute("SELECT * FROM booking WHERE customer_id=%s", [cust_id])
    for row in cursor.fetchall():
        booking_details.append(row)

CodePudding user response:

You don't need to loop, you can fetch all the details in one query:

for_quicksort = [1, 5, 9, 11, 19]


for i in range(len(for_quicksort)):
    fetch_booking_details = cursor.execute(
        "SELECT * FROM booking WHERE customer_id IN (?, ?, ?, ?, ?)",
        (for_quicksort,)
    )
    booking_details = fetch_booking_details.fetchall()
  • Related