我有一个程序在' 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()
答案 0 :(得分:3)
我认为你在第三行到最后一行的return语句需要缩进一级。否则你的while循环将永远运行,因为True将永远是真的!
答案 1 :(得分:0)
在replaceid(connection, servername.strip())
start1()
后,您可能需要添加一个中断语句
在异常子句结束后,您可能还需要一个break语句。