I have created 2 class , I need have 1 list of one class inside another class. This class is generated from database select
I have a problem with iterating objects list inside objects list:
MySQL Schema
CREATE TABLE tablefruit (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
shopid INT(6) NOT NULL,
`name` VARCHAR(200) NULL,
`description` VARCHAR(200) NULL,
);
CREATE TABLE tableshop (
shopid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(200) NULL,
`description` VARCHAR(200) NULL,
);
TABLE CONTENTS:
-- tablefruit
id shopid name description
1 1 ftest1 ftestdesc1
2 1 ftest2 ftestdesc2
-- tableshop
shopid name description
1 stest1 stestdesc1
2 stest2 stestdesc2
3 stest3 stestdesc3
"""
Python code
import mysql.connector
from mysql.connector import Error
connection = None
try:
connection = mysql.connector.connect(host='127.0.0.1',
database='database',
user='root',
password='password',autocommit=True)
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL database... MySQL Server version on ",db_Info)
except Error as e :
print ("Error while connecting to MySQL", e)
class fruit:
id=None
shopid=None
name=None
description=None
def db_select(self):
sql = "select shopid,name,description from tablefruit where id = %s"
val = (self.id,)
cursor = connection.cursor(buffered=True)
cursor.execute(sql,val)
records = cursor.fetchall()
for row in records:
self.shopid = row[0]
self.name = row[1]
self.description = row[2]
cursor.close()
connection.commit()
def __init__(self,id=None)
self.id=id
self.db_select()
class shop:
shopid=None
name=None
description=None
fruits = list()
def db_select(self):
sql = "select name,description from tableshop where shopid = %s"
val = (self.shopid,)
cursor = connection.cursor(buffered=True)
cursor.execute(sql,val)
records = cursor.fetchall()
for row in records:
self.name = row[0]
self.description = row[1]
cursor.close()
connection.commit()
def load_fruit(self):
sql = "select id from tablefruit where shopid = %s"
val = (self.shopid,)
cursor = connection.cursor(buffered=True)
cursor.execute(sql,val)
records = cursor.fetchall()
for row in records:
fruits.append(fruit(row[0]))
cursor.close()
connection.commit()
def __init__(self,shopid=None):
self.shopid=shopid
self.db_select()
self.load_fruit()
#MAIN
shops=list()
sql = "select shopid from tablefruit"
cursor = connection.cursor(buffered=True)
cursor.execute(sql)
records = cursor.fetchall()
for row in records:
shops.append(shop(row[0]))
cursor.close()
connection.commit()
for shop in shops:
for fruit in shop.fruits:
print(fruit.name,fruit.description)
My code : https://pastebin.com/0Qck4FbH
and my output is:
ftest1 ftestdesc1
ftest2 ftestdesc2
ftest1 ftestdesc1
ftest2 ftestdesc2
ftest1 ftestdesc1
ftest2 ftestdesc2
why is this the output? The output I expect would be:
ftest1 ftestdesc1
ftest2 ftestdesc2