简体   繁体   中英

How to exit while loop properly?

I have a program that runs through a list of names in 'serverlist.txt'. The user selects the database they want to search in by choosing option 1 or option 2. The program will run through all names in the list and provide the id tied to each name.

Name: Jupiter ID: 23 Name: Mars ID: 26 Name: Mercury ID: 27

This works fine but it doesn't stop. When the list is complete, it loops through everything all over again.

How do I stop it from going through the list more than once?

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

I think your return statement on the third to last line needs to be indented one level. Otherwise your while loop will run forever, because True will always be true!

You might want to add a break statement after you call replaceid(connection, servername.strip()) in start1()

You might also want a break statement after the exception clause ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM