簡體   English   中英

使用 pymssql 進行 n 次迭代后輸入確認的 For 循環

[英]For Loop with input confirmation after n iterations with pymssql

我正在使用以下代碼使用字典更新數據庫表:

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()

我的字典有幾千個詞條。 是否可以在代碼中添加一個部分,詢問在將 1000 行寫入數據庫后是否應該繼續?

我試過這樣的事情:

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()

但這不能正常工作。

基於計數器有條件地初始化輸入應該可以工作。 初始化輸入后,您還應該將計數器重置為 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()

在循環中有一個input語句是可以的,但是執行將停止,直到輸入一些內容。 然后,您必須檢查輸入的內容以確定是否要繼續:

cursor = conn.cursor()
sql = 'UPDATE table SET R = %s WHERE %s = ID' # moved out of the loop
counter = 0
for key in dRt:
    counter += 1                         
    x = dRt[key]                                 
    cursor.execute(sql, (x, key))     # moved higher in the loop
    if counter == 1000:               # now we have done the next 1000 updates
        reply = input("Beenden? Enter drücken!\n")
        if reply == '':
            break # anything else entered than just enter, for example "geh", and we continue
        counter = 0
conn.commit()
conn.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM