簡體   English   中英

如何正確退出while循環?

[英]How to exit while loop properly?

我有一個程序貫穿“ serverlist.txt”中的名稱列表。 用戶通過選擇選項1或選項2來選擇要搜索的數據庫。該程序將遍歷列表中的所有名稱,並提供與每個名稱相關聯的ID。

名稱:木星ID:23名稱:火星ID:26名稱:水星ID:27

這工作正常,但不會停止。 列表完成后,它將再次遍歷所有內容。

如何阻止它多次瀏覽列表?

import pypyodbc
import os

def replaceid(connection, servername):
    try:
        cursor = connection.cursor()

        SQLCommand = ("SELECT Name, Location_ID "
            "FROM dbo.Server_ID "   # table name
            "with (nolock)"
            "WHERE Name = ?")
        Values = [servername]
        cursor.execute(SQLCommand,Values)
        results = cursor.fetchone()
        if results:

            print (" Name: " + results[0] + " ID: " + str(results[1]))
            print (" ")
            locationid(results, connection, servername)
        else:
            print (" ID for " + servername + " does not exist.")
            print (" ")
            connection.close()
    except:
        print("Database is down or you are not connected to network.")
        exit()

def start1():

    os.system('cls' if os.name == 'nt' else 'clear')
    array = []
    local = input('\n\n Type option 1 or 2: ')
    while True:
        with open("serverlist.txt", "r") as f:
            for servername in f:
                try:                

                    if local in ['1']:
                        connection = pypyodbc.connect('Driver={SQL Server};Server=db1;Database=WinOasis;Trusted_Connection=yes;')
                    elif local in ['2']:
                        connection = pypyodbc.connect('Driver={SQL Server};Server=db2;Database=WinOasis;Trusted_Connection=yes;')
                    else:
                        return
                except pypyodbc.Error as ex:
                    sqlstate = ex.args[0]
                    if sqlstate == '28000':
                        print ("You do not have access.")

                replaceid(connection, servername.strip())
    return

start1()

我認為您在第三行到最后一行的return語句需要縮進一個級別。 否則,您的while循環將永遠運行,因為True永遠都是true!

您可能要在start1()調用replaceid(connection, servername.strip())后添加一個break語句

您可能還需要在exception子句結束后使用break語句。

暫無
暫無

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

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