Forums

"MySQL Connection not available" error occurring randomly

I get the following error regularly, but randomly: OperationalError: (OperationalError) MySQL Connection not available.

If I reload the page it will go away.

I'm pretty new to using python so I'm imagining it's something wrong with my code, but don't know where to look - would this have to do with how I connect to the database or would it be related to specific queries? Any help would be appreciated, I'm at a bit of a loss.

Are you using a web framework? If so, which? That would help us debug.

Hi Giles, Yeah - I'm using pyramid with sqlalchemy

Does it happen at a consistent place in your code? We sometimes see a similar error in our own logs, and it does always happen at the same spot, and we were toying with the idea of just wrapping it in a try/except, with some reconnect/retry code...

Right, one possibility is that your connections to the database are timing out.

For example, your app (perhaps indirectly via sqlalchemy or Pyramid) might be keeping a cache of connections to the database. When you hit the page, it gets a connection from the cache, but that connection has timed out, so it gives you an error. The error might also remove the connection from the cache (because it's obviously broken), so when you hit the app again, it has to create a new one, which works.

Unfortunately I don't know enough about your specific setup to be sure. But connection caching is normally something the framework would handle for you -- perhaps there are some parameters to control how much caching it does?

Hi Giles and Harry - thanks for your responses, they give me something to work from.. I'll check into the caching parameters and see what I can figure out. I'll post here once I get it working. You guys are great.

No problem!

I have the same issue using Django 1.6 with Python 3.3 and South migrations.

SQLAlchemy's default is to assume that a connection is always available and ready to use. You can change the behaviour with what SQLAlchemy calls pessimistic disconnect handling: http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html#disconnect-handling-pessimistic.

@geordi - Which MySQL backend are you using? As far as I can tell, Django on Python 3 with MySQL is not well supported. If you look on this page, you'll see that the backend that Django supports is not available for Python 3.