简体   繁体   中英

Is there a way to stop the execution of a mysql query in python if a python exception occurs?

I'm running a python script that executes mysql queries with many rows. The query takes a lot of time to run and sometimes I need to stop the script to change something or to start over. Is there a way to tell the mysql server that the script is terminating (for example if a KeyboardInterrupt exception occurs) and that the result of the query is no longer needed?

I tried closing the mysql connection and it didn't work. The execution of the query keeps on going.

I know that I can kill the query from the server directly but I would like the script to do it by itself.

I'm using the mysql-connector-python library, version is 2.0.2.

You can wrap you code in try except block and kill the query once exception raised. Something like that:

pid = <get the pid of the query>
try:
  .... your code
except:
  cursor.execute('kill %s', pid)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM