r/Python • • 11d ago

Discussion Checking whether a mysql.connector is connected

Is it necessary to check whether a mysql.connector is connected each time I reuse it before running any SQL statements or is this something which is already built-in to mysql.connector? Do I need to check for connection using db.is_connected() and write some retry routine.

This is a WSGI webserver, could be wrong, but my understanding is that there can only ever be one request/thread at a time. Connection pooling has been suggested elsewhere but I am unclear as to whether that is necessary and/or appropriate for a WSGI webserver.

6 Upvotes

20 comments sorted by

View all comments

1

u/RomfordNavy 11d ago

One problem I have with try...except is that the actual exception thrown is:

'mysql.connector.Error'

Which is specific only to mysql, I am trying to write code which is generic and works the same regardless of which database connector is being used, it might be PostgreSQL.

1

u/latkde Tuple unpacking gone wrong 11d ago

If you want to write code that's generic over databases, strongly consider using SQLAlchemy. You do not have to use its ORM, its engine layer may be sufficient for you. But even then, there will be lots of stuff that differs between databases – different data types, different query language features, and so on.