How to fix sqlmodel/sqlalchemy Lost connection to MySQL server during query

Problem

When using SQLModel or SQLAlchemy in your script, you see the following error message:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
(Background on this error at: https://sqlalche.me/e/20/e3q8)

Solution

Typically this error occurs if you have either your username or your password wrong. Rarely, it can also be caused by a network issue or you trying to connect to the wrong host.

Check your connection string and make sure that the credentials are correct.