如何在 mysql 数据库中迭代 fetchone() 的输出列表

How to interate over an output list from fetchone() in mysql database

我目前正在创建一个类似于银行账户的主菜单。

def main_menu():
    print("Main Menu")
    print("0 - Quit")
    print("1 - Open Account")
    print("2 - Check Balance")
    print("3 - Close Account")


loop = True
while loop:
    main_menu()
    choice = input("Enter your choice: ")
    choice = int(choice)
    if choice == 0:
        exit(loop)
    elif choice == 1:
        name_on_account = input("Name on account: ")
        balance = float(input("Enter Initial Balance: "))
        print("---Account successfully created---")
        print("Account number:", account_no())
        print("Name on account:", name_on_account)
        print("Balance:", balance)
        print("Account opened on:", now)
        cur.execute("""
        INSERT INTO account(name_on_account, balance) VALUES 
        ("%s", "%s");""", (name_on_account, balance))
        connection.commit()
    elif choice == 2:
        print("Checking account balance")
        account_number = input("Enter account number: ")
        print("---Checking account balance---")
        print("Account number:", account_number)
        cur.execute("""SELECT * from account;
        """)
        account_no1 = cur.fetchone()
        for i in account_no1[0]:
            if account_number == i:
                cur.execute("""select name_on_account from account where account_no = "%s";
                        """, (account_number,))
                name1 = cur.fetchone()
                print(name1)
                name2 = ''.join(map(str,name1))
                name3 = int(name2)
                print("Name on account:", name3)
                cur.execute("""select balance from account where account_no = "%s";
                        """, account_number)
                balance1 = cur.fetchone()
                balance2 = ''.join(map(str,balance1))
                balance3 = int(balance2)
                print("Balance:", balance3)
                cur.expecute("""select account_open_date from account where account no = "%s";
                        """, account_number)
                date1 = cur.fetchone()
                date2 = ''.join(map(str, date1))
                date3 = int(date2)
                print("Account opened on:", date3)
                connection.commit()
            else:
                print("Error: Invalid account number")

我现在不担心选项 3,但我在选项 2 上遇到了问题。

当一个人选择选项 1 时,他们将输入他们的姓名和存入他们银行帐户的金额。

此信息将存储在mysqltable账户中(account_no、name_on_account、余额、account_open_date、account_status) .

这意味着account_no是自动递增的,account_open_date默认为curdate(),account_status默认为"open")。

然而,在选项 2 中,当一个人输入他们的帐号时;它应该 return 支持他们所有的信息如何在选项 1 中显示。

我遇到的问题是,如何使用 fetchone() 有效地遍历此人的信息并能够使用 (account_no = account_number) (如果您对更好的实现方式有更好的建议,请在下方评论)

这是我收到的错误消息: 追溯(最近一次通话): 文件“(出于隐私目的删除)” 对于 account_no1[0] 中的我: 类型错误:'int' 对象不可迭代

感谢您的帮助!

pymysql(以及大多数其他 python mysql 客户端)在您调用 fetchone() 时返回一个元组,并且元组中的每个条目最多匹配您正在查询的 table 中定义的数据类型。那么让我们看看您的代码:

elif choice == 2:
    print("Checking account balance")
    account_number = input("Enter account number: ")
    print("---Checking account balance---")
    print("Account number:", account_number)
    cur.execute("""SELECT * from account""")
    account_no1 = cur.fetchone()
    for i in account_no1[0]:

此处您查询 account table 中的所有列和所有行,读取第一行,然后迭代该行第一列中的任何内容。但这 可能 只是一个 id 列,这可能就是您收到错误的原因:整数不可迭代。就好像写for i in 10,Python不明白什么意思

如果您想遍历所有返回的行,您可以这样做:

    cur.execute("""SELECT * from account;
    """)
    for row i in cur.fetchall():
        # Each iteration "row" is a tuple of values corresponding to the table's columns

虽然这有点傻。您将从数据库中返回所有行,然后遍历它们并查找特定的帐号。为什么不将其作为查询的一部分呢?

    nrows = cur.execute("SELECT * from account where account_no=%s", (account_number,))
    if nrows == 0:
        # Account number not found, do something
    else:
        row = curs.fetchone()
        # row now contains all of the values from the discovered 

请注意,您不需要在 %s 占位符两边加上引号,也不需要分号。客户端为您完成所有这些转换。

另请注意,您不应该 select * 来自 tables。如果 table 定义更改为包含更多列怎么办?只需 select 您实际需要的少数几列,然后如果稍后将更多列添加到 table,您的代码将根本不需要更改,您也不会请求更多的数据你需要。所以更像是:

nrows = cur.execute("SELECT name, balance, date_opened from account where account_no=%s", (account_number,))
if nrows > 0:
    name, balance, date_opened = curs.fetchone()