简体   繁体   English

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

[英]Retrieving data in Python from two MySQL tables?

I'm using Python and I'm trying to retrieve data from two mySQL tables(name = deal_info and profile) in the same database (name = begin). 我正在使用Python,并且试图从同一数据库(名称= begin)中的两个mySQL表(名称= deal_info和配置文件)中检索数据。 The two tables are not linked or do NOT have the same primary key, but I get the error 这两个表未链接或没有相同的主键,但是出现错误

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

Below is the code 下面是代码

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()

Per the MySQL.connector docs , you need to fetch results before executing any other statement: 根据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. 在这种情况下,必须确保在同一连接上执行任何其他语句之前,先获取结果集的所有行,否则将引发InternalError(找到未读结果)异常。

So simply run your looped print lines after cursor.execute() : 因此,只需在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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM