If Else 条件 python

If Else condition on python

我试图在 for 循环之后放置一个条件。如果检索到的行不等于零,它将打印可用词,但是如果我要输入一个未存储在我的数据库中的值,它将 return 一条消息。我的问题是,如果我输入的值没有存储在我的数据库中,它就不会转到 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() 

在 python 中,您应该检查 None 而不是 NULL。在你的代码中你可以只检查对象,如果它不是 None 那么控制应该进入 if 否则 else 将被执行

for row in rows:
    if row:
        print('Available')
    else:
        print('No available copies of the said book in the library')

UPDATE after auther edited the question:

现在在 for 循环中,您应该检查列值而不是整个 row。如果您的列名是假设 quantity 那么 if 语句应该是这样的

if row["quantity"] != 0:

首先调用 python 中的 NULL None。 下一个: 根据文档: “该方法获取查询结果集的所有(或所有剩余)行和 returns 元组列表。如果没有更多行可用,它 returns 一个空列表。 “ 空列表不是 None

>>> row = []
>>> row is None
False

所以你需要像这样重新设计你的 if 语句:

for i in rows:
    if i:
        blah-blah
    else:
        blah-blah-blah

除了 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')