Keeping an active connection on a MySQL server has a high cost in terms of memory, so MySQL closes connections that have been unused for a certain amount of time. This is normal for all MySQL servers; if you want to write code that only runs queries every now and then, it's best to create a new connection each time. An even better option -- though it does require more setup -- is to use a connection manager, like the one built into SQLAlchemy. That will keep a pool of connections, discarding the ones that have timed out, and opening new ones as necessary, so you just need to ask it for a connection and it will give you a working one.