这个函数在我的数据库中搜索记录。除了 if 条件之外,即使条件为真,else 语句(“未找到记录”)也会继续执行。 OUTPUT screenshot
def displaySearchAcc():
try:
command = "SELECT * FROM BANK"
mycursor.execute(command)
s = mycursor.fetchall()
ch = input("Enter the account number to be searched : ")
for i in s:
i = list(i)
if i[0] == ch:
print("*" * 125)
print("ACCNO", "NAME", "MOBILE", "EMAIL", "ADDRESS", "CITY", "COUNTRY", "BALANCE")
print("=" * 125)
for j in i:
print("%14s" % j, end=' ')
print()
else:
print("record not found")
except:
print("Table not found")
答案 0 :(得分:0)
def displaySearchAcc():
try:
command = "SELECT * FROM BANK"
mycursor.execute(command)
s = mycursor.fetchall()
ch = input("Enter the account number to be searched : ")
for i in s:
if i[0] == ch:
print("*" * 125)
print("ACCNO", "NAME", "MOBILE", "EMAIL", "ADDRESS", "CITY", "COUNTRY", "BALANCE")
print("=" * 125)
for j in i:
print("%14s" % j, end=' ')
print()
else:
print("record not found")
except:
print("Table not found")
答案 1 :(得分:0)
你甚至不需要 for 循环。您可以仅使用 SQL 语句执行搜索,这比您使用的迭代方法快得多。假设列名是 account_number
def displaySearchAcc():
account_no = input("Enter the account number to be searched : ")
command = f"SELECT * FROM BANK WHERE account_number = '{account_no}'"
row = mycursor.fetchone()
if row is not None:
print("*" * 125)
print(
"ACCNO", "NAME", "MOBILE", "EMAIL", "ADDRESS", "CITY", "COUNTRY", "BALANCE"
)
print("=" * 125)
for col in row:
print("s" % col, end=" ")
print()
else:
print("Record not found")
如果您真的坚持使用迭代方法,那么您所犯的错误就是行i = list(i)
。 i
已经是一个列表,通过将 i 放入列表中,您正在制作列表(二维列表),这会扰乱您的迭代。
def displaySearchAcc():
try:
command = "SELECT * FROM BANK"
mycursor.execute(command)
all_rows = mycursor.fetchall()
account_no = input("Enter the account number to be searched : ")
for row in all_rows:
if row[0] == account_no:
print("*" * 125)
print("ACCNO", "NAME", "MOBILE", "EMAIL", "ADDRESS", "CITY", "COUNTRY", "BALANCE")
print("=" * 125)
for col in row:
print("%14s" % col, end=' ')
print()
break; # No need to iterate further
else:
print("record not found")
except:
print("Table not found")
另外,使用更好的变量名。