2

I'm using a python program to manipulate a MySQL database.

When trying to use the windows server 2012 task scheduler it never work, the report does say that it was successful but there is not result.

After using a powershell script to call the python program it still doesn't work when used by the task scheduler (while it does work when I execute it myself).

Here part reported as bugged:

try:
    dbconfig = read_db_config()
    conn = MySQLConnection(**dbconfig)
    cursor = conn.cursor()
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC'  OR filliere='ETI' OR filliere='CGP'"
    cursor.execute(delstatmt)
    conn.commit()
except Error as e:
    print(e)

finally:
    cursor.close()
    conn.close()

The error being at the line "cursor.close()": UnboundLocalError: local variable 'cursor' referenced before assignment

Note: It does work when not handled by the task scheduler.

Edit: Shubham Namdeo solution work, though the problem just switched to conn.close() I also moved it in the "try". I don't understand why it didn't work in the first form since it worked when I execute it myself. While other error appeared they are not related to this question. Here is the final code:

try:
    dbconfig = read_db_config()
    conn = MySQLConnection(**dbconfig)
    cursor = conn.cursor()
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC'  OR filliere='ETI' OR filliere='CGP'"
    cursor.execute(delstatmt)
    conn.commit()
    cursor.close()
    conn.close()
except Error as e:
    print(e)
Eric Godard
  • 179
  • 12

1 Answers1

1

Quoting my own comment here

Have you checked whether conn = MySQLConnection(**dbconfig) is working correctly? If it is not, then no cursor will be ever created and in finally python will raise error.

Try using this code instead of yours:

try:
    dbconfig = read_db_config()
    conn = MySQLConnection(**dbconfig)
    cursor = conn.cursor()
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC'  OR filliere='ETI' OR filliere='CGP'"
    cursor.execute(delstatmt)
    conn.commit()
    cursor.close()
    conn.close()

except Error as e:
    print(e)

This might solve your problem.

Shubham Namdeo
  • 1,845
  • 2
  • 24
  • 40