我试图在for循环后放置一个条件。如果检索到的行不等于零,它将打印出可用的单词,但是,如果我要输入未存储在数据库中的值,它将返回一条消息。我的问题是,如果我要输入未存储在数据库中的值,则不会进入else语句。我是新来的。我在此功能中会犯什么错误?
def search(title):
query = "SELECT * FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
rows = cursor.fetchall()
for row in rows:
if row != 0:
print('Available')
else:
print('No available copies of the said book in the library')
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
def main():
title = input("Enter book title: ")
search(title)
if __name__ == '__main__':
main()
除了0 / NULL混淆之外,您的逻辑是错误的。如果没有匹配的行,您将不会获得0作为行的值;实际上,您根本不会获得任何行,甚至也不会进入for循环。
更好的方法是简单地运行COUNT查询,使用获取单个结果fetchone()
,然后直接检查。
query = "SELECT COUNT(*) FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
result = cursor.fetchone()
if result != 0:
print('Available')
else:
print('No available copies of the said book in the library')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句