Oh, wait a sec... Does your MySQL connection go idle for some time before this query? If so, it's possible the connection is being idled out, but MySQL only actually notices that it's gone when you try and perform your next query.
In your script where you see the problem, you could try calling the ping()
method on the connection object (not the cursor) just prior to performing the query - if the connection is lost, that should either automatically reconnect (problem solved) or it should raise an OperationalError
in which case you'll have to create a new connection.
Apologies for the vagueness, but I'm dredging this up from when I implemented a MySQL connection pool in Python many moons ago and I can't quite recall whether MySQLdb has automatic reconnection enabled or not. In any case, I did discover that one should never rely on long-running transactions in MySQL - if it's going to take more than a few seconds then don't bother. If you're only reading, of course, then transactions don't really matter so things are a lot less critical.
EDIT: The docstring for ping()
indicates that if you call conn.ping(True)
then it sets the automatic reconnect flag persistently for that connection, so perhaps you can just do that once when you first connect and not worry about it.
Just be aware that any disconnect (including due to idling) implicitly rolls back any outstanding transaction, as I mentioned earlier, which is why I tend to prefer manual reconnection because then if a transaction was pending you can raise an exception in Python so your code doesn't push the DB into an inconsistent state. Automatic reconnection seems more convenient, but if you're using transactions then it can make issues very much harder to track down.