gpt4 book ai didi

python - 在Python中从两个MySQL表中检索数据?

转载 作者:行者123 更新时间:2023-11-29 20:57:51 31 4
gpt4 key购买 nike

我正在使用Python,并且尝试从同一数据库(name = begin)中的两个mySQL表(name = deal_info和profile)检索数据。这两个表未链接或没有相同的主键,但我收到错误

  raise errors.InternalError("Unread result found.")
mysql.connector.errors.InternalError: Unread result found.

下面是代码

import mysql.connector
from decimal import *

cnx = mysql.connector.connect(user='root', password = 'xxx', database='begin')
cursor = cnx.cursor()

query_deal_info = ("SELECT mrp, qty_remain, deal_price, qty, asp FROM deal_info WHERE deal_id = %s")
deal_id = int(input("Enter the deal id:"))
cursor.execute(query_deal_info,(deal_id,))
query_profile = ("SELECT user_id, abp1, abp2, abp3, abpf FROM profile WHERE user_id = %s")
user_id = int(input("Enter the user id:"))
cursor.execute(query_profile,(user_id,))

for (mrp, qty_remain, deal_price, qty, asp) in cursor:
print("The MRP for the deal is {}".format(mrp))
print ("The deal price is {}, asp is {} and qty is {}".format(deal_price, asp, qty))

for (user_id, abp1) in cursor:
print("The ABP1, 2, 3 and f for the deal is {}, {}".format(user_id, abp1))

cursor.close()
cnx.close()

最佳答案

根据 MySQL.connector docs ,您需要在执行任何其他语句之前获取结果:

In this case, you must be sure to fetch all rows of the result set before executing any other statements on the same connection, or an InternalError (Unread result found) exception will be raised.

因此,只需在 cursor.execute() 之后运行循环打印行即可:

cnx = mysql.connector.connect(user='root', password = 'xxx', database='begin')
cursor = cnx.cursor()

# DEAL INFO
query_deal_info = "SELECT mrp, qty_remain, deal_price, qty, asp \
FROM deal_info WHERE deal_id = %s"
deal_id = int(input("Enter the deal id:"))
cursor.execute(query_deal_info,(deal_id,))

for (mrp, qty_remain, deal_price, qty, asp) in cursor:
print("The MRP for the deal is {}".format(mrp))
print ("The deal price is {}, asp is {} and qty is {}".format(deal_price, asp, qty))

# PROFILE
query_profile = "SELECT user_id, abp1, abp2, abp3, abpf \
FROM profile WHERE user_id = %s"
user_id = int(input("Enter the user id:"))
cursor.execute(query_profile,(user_id,))

for (user_id, abp1) in cursor:
print("The ABP1, 2, 3 and f for the deal is {}, {}".format(user_id, abp1))

cursor.close()
cnx.close()

关于python - 在Python中从两个MySQL表中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37489052/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com