Skip to content
Advertisement

Why can’t I loop through and drop databases?

There is a scenario where I want to go through and remove all databases that have specific text in the database name. It always drops one database and then does nothing. How can I fix this?

def connect():
    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        password=""
    )
    return mydb


    mydb = connect()

    mycursor = mydb.cursor(buffered=True)

    mycursor.execute("SHOW DATABASES")

    for x in mycursor:
        if ("_tenant_billing" in str(x[0]).lower()):
            print(x[0])
            db = x[0]
            mycursor.execute("DROP DATABASE " + db)
            mydb.commit()

Advertisement

Answer

Posting as answer.

Do fetchall() then iterate over that

databases = mycursor.execute("SHOW DATABASES").fetchall()

for database in databases:
    # your stuff
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement