Search code examples
pythonpython-3.xpymysql

TypeError: 'int' object is not iterable when executin SQL with SET in python3


I am creating set, to prevent duplicates while I am deleting old folders on server depending on status in column of table. But when I try to run this script

cursor = connection.cursor()
sql="SELECT id, name, state FROM domain WHERE state='2'"
cursor.execute(sql)
records = cursor.fetchall()
print("Total number of records for deleting is: ", cursor.rowcount)

deleted = set(cursor.execute("select distinct name from domain where state = 2"))
active = set(cursor.execute("select distinct name from domain where state != 2"))

to_delete = deleted - active

print('Printing each domain record', "\n")
for row in records:

    print("id = ", row["id"], )
    print("name = ", row["name"])
    print("state  = ", row["state"], "\n")

    id = row["id"]
    name = row["name"]
    state = row["state"]

    if to_delete == 2:
        try:
            if os.path.exists('/data/sa/' + name):
                print('found records for deleting: ' + name, "\n")
                print("Total number of records for deleting is: ", cursor.rowcount)
                input("Press Enter to continue...")
                shutil.rmtree('/data/sa/' + name)
                print('records deleted')            
            else:
                print('no Directory found')
        #    pass
        except Exception as error:
            print("Directory already deleted or never existed")
    else:
        print('no records for deleting found')
        print('domain', name)
        print('hast state', state, "\n")

quit()
connection.close()

I've to this error

Traceback (most recent call last):
  File "mazani_old_zaznamu2.py", line 21, in <module>
    deleted = set(cursor.execute("select distinct name from domain where state = 2"))
TypeError: 'int' object is not iterable

I asume that's because there is alot of domain rows, so I have to sort them somehow make iterable, but I dont know how is that possible.


Solution

  • The execute method doesn't return the rows itself, just the number of affected rows.

    To get the results, try:

    cursor.execute("select distinct name from domain where state = 2")
    deleted = set(d['name'] for d in cursor.fetchall())