-1

I'm doing some work using Python to update a MySQL database. Many instances of my script can be running at one time, so occasionally I will get LOCK error messages from the MySQL server:

mysql.connector.errors.DatabaseError: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

If these occur, I would like to retry the operation. I can use a basic except Exception as e statement, but that traps all errors, which is not what I need.

How can I trap only the LOCK errors generated by MySQL?

cursor = mysql.connector.connect(host="myhost.com", user=username, passwd=password, db=schema, auth_plugin='mysql_native_password')

sql = "UPDATE table SET mycolumn = 'mydata'"

while True:
    try:
        cursor.execute(sql)
        break
    except Exception as e:   # I only want to catch LOCK errors here
        print(repr(e))

    except:
        print(sql)
        raise

2 Answers 2

1

You can extract the error code and perform certain actions based on it. An example for the pymysql module, for yours - refer to the documentation.

import pymysql
from pymysql.err import DatabaseError

try:
    mydb = pymysql.connect(
        host = "127.0.0.1",
        port = 123123,
        user = "user id",
        password = "!!!!!!!"
        )
except DatabaseError as e:
    err_code = e.args[0]
    if err_code == 2003:
        print('bad connection string')
    else:
        raise

Output:

bad connection string
0

the error number is 1205

So catch the this number

import mysql.connector
from mysql.connector import errorcode

cursor = mysql.connector.connect(host="myhost.com", user=username, passwd=password, db=schema, auth_plugin='mysql_native_password')

sql = "UPDATE table SET mycolumn = 'mydata'"

while True:
    try:
        cursor.execute(sql)
        break
        if err.errno == 1205 :
            print("Lock wait timeout exceeded")
        else:
            print(sql)
            raise
3
  • Where is the except? Some cute thing with try break?
    – doug65536
    Commented Dec 12, 2021 at 2:39
  • you don't need it as i have show in my answer
    – nbk
    Commented Dec 12, 2021 at 16:07
  • How does the exception magically jump over the break and stop at if? Execute throws and the existence of a break means make a landing pad for the exception there and goto the line after the break in the landing pad? Or what?
    – doug65536
    Commented Dec 13, 2021 at 2:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.