Python MySQL ReferenceError: weakly-referenced object no longer exists

cursor object uses connection object.
When your get_user_by_username function finishes execution,
the connection to mysql gets closed therefore cursor cannot exists as well.
Having the function return both connection and cursor will work.

import mysql.connector

def get_user_by_username(username):
    mydb = mysql.connector.connect(
        host="localhost",
        user=username,
        passwd="k3gc8pHPvEtGqND",
        database="test"
        )

    mycursor = mydb.cursor()

    mycursor.execute("SELECT * FROM users")
    return mydb, mycursor

mydb, mycursor = get_user_by_username("testuser")
for x in mycursor:
    print(x)