从两个MySQL表中检索Python中的数据?

时间:2016-05-27 17:14:28

标签: python mysql

我正在使用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()

1 个答案:

答案 0 :(得分:0)

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

  

在这种情况下,您必须确保获取结果集的所有行   在执行同一连接上的任何其他语句之前,或者   将引发InternalError(未读结果)异常。

只需在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()