-1

This is my code. I want to select data from db and set as this class object.

import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                 user="me",         # your username
                 passwd="1000",  # your password
                 db="something")        # name of the data base

cur = db.cursor()

cur.execute("SELECT img, color, title, divv  FROM p_div_gerd WHERE chest = '1'")


class Testing:

    def __init__(self, img, color, title):
            self.img = img
            self.color = color
            self.title = title



# print all the first cell of all the rows
for row in cur.fetchall():

    "t" . str(row[4]) = Parish (row[0], row[1], row[2])


db.close()


print(t1.img)
print(t1.color)
print(t1.title)

This line is incorrect:

        "t" . str(row[4]) = Parish (row[0], row[1], row[2])

I want to have something like:

t1
t2
t3

How should I edit that? row[4] which backs to divv column is integer.

niloofar
  • 2,244
  • 5
  • 23
  • 44

2 Answers2

0
row = [1, 2, 3]
for i in row:
    print ("t"+str(i))

That prints out:

t1
t2
t3

I have no idea why you are trying to assigned a value to a string. You should use an array or dictionary to store those values. I hope that helps.

I think this is the question you want to ask: How can you dynamically create variables via a while loop?

Community
  • 1
  • 1
Jordan Stewart
  • 3,187
  • 3
  • 25
  • 37
0

Don't try to create variable names from data. Instead, use an array or a dictionary.

Dictionary style:

t = {}
for row in cur.fetchall():
    t[str(row[4])] = Parish (row[0], row[1], row[2])

...

print(t["1"].img)
print(t["1"].color)
print(t["1"].title)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • The output of your code is this for me: `t [str(row[4])] = Parish (row[0], row[1], row[2]) IndexError: tuple index out of range` – niloofar Apr 14 '16 at 06:14