Search code examples
pythonpymssql

For Loop with input confirmation after n iterations with pymssql


I am updating a database table with a dictionary with this code:

cursor = conn.cursor()
for key in dRt:                          
    x = dRt[key]                          
    sql = 'UPDATE table SET R = %s WHERE %s = ID'
    cursor.execute(sql, (x, key))
conn.commit()
conn.close()

My dictionary got several thousand entries. Is it possible to add a part to the code which asks, after writing 1000 rows into the database, if it should continue?

I tried something like this:

cursor = conn.cursor()
counter = 0
for key in dRt:                         
    x = dRt[key]                         
    sql = 'UPDATE table SET R = %s WHERE %s = ID'
    if counter == 1000:
        break
    eingabe = input("Beenden? Enter drücken!\n")
    cursor.execute(sql, (x, key))
conn.commit()
conn.close()

But this does not work correctly.


Solution

  • Conditionally initialising an input based on counter should work. After initialising an input you should also reset the counter to 0.

    cursor = conn.cursor()
    counter = 0
    for key in dRt:
        counter += 1                         
        x = dRt[key]                         
        sql = 'UPDATE table SET R = %s WHERE %s = ID'
        if counter == 1000:
            input("Beenden? Enter drücken!\n")
            counter = 0
    cursor.execute(sql, (x, key))
    conn.commit()
    conn.close()