Home > Blockchain >  SQLITE query for words in a list - For loop stops after first word
SQLITE query for words in a list - For loop stops after first word

Time:11-12

I have the following code:

con =sqlite3.connect('library.db')
cur = con.cursor()
data=cur.execute('''SELECT * FROM Database''')

for word in word_list:
iteration_counter = 0
    for column in data.description:
        query = f'''SELECT {column[0]} FROM Database WHERE LOWER({column[0]}) = ?'''
        cur.execute(query,(word,))
        output = cur.fetchone()
        iteration_counter  = 1
        print(iteration_counter)

word_list is a list variable that lowercase words from an input text. I want the function to query each word in the list to find out which column the word is placed under in the database. In order to verify that the for loop works, I make the function print the variable iteration_counter which is incremented for every column that is queried. For the first word in the list, this demonstrably works. For every other word however - the loop stops at 1.

What am I doing wrong?

CodePudding user response:

Program changes the "value" of the cursor (data) while it is iterating over the cursor (for column in data.description:).

Perhaps use the connection's execute method for the data SELECT eg data=con.execute('''SELECT * FROM Database''')

Or instantiate a second cursor for the query SELECT by adding line cur2 = con.cursor after the connect then using cur2 inside the inner for instead of cur.

  • Related