mysql 为什么数据库中的所有产品都没有出现在输出中(只有一个产品列表出现)我想要所有列表,我分享了一张table照片

qoefvg9y  于 2023-05-16  发布在  Mysql
关注(0)|答案(1)|浏览(76)

enter image description here是一个python代码,在输出中只显示一个列表。我想要所有列表请帮助我解决这个问题

import mysql.connector
from mysql import connector

def get_all_products():
    cnx = mysql.connector.connect(user='root', password='R#@26rads26',
                                  host='127.0.0.1',
                                  database='gs')
    cursor = cnx.cursor()
    query = "SELECT * FROM gs.products"
    cursor.execute(query)
    response = []
    for (product_id, name, uom_id, price_per_unit) in cursor:
        response.append({
            'product_id': product_id,
            'name': name,
            'uom_id': uom_id,
            'price_per_unit': price_per_unit
        })
        cnx.close()
        return response

if __name__ == '__main__':
    print(get_all_products())
3npbholx

3npbholx1#

将最后一行移出for循环应该可以解决这个问题:

for (product_id, name, uom_id, price_per_unit) in cursor:
        response.append({
            'product_id': product_id,
            'name': name,
            'uom_id': uom_id,
            'price_per_unit': price_per_unit
        })
    # The following lines should not have been inside the for loop
    cnx.close()
    return response

相关问题