Forums

MySql Database has gone away(2006)

Hey, I just deployed python project that uses flask and peewee and mysql db. After few uses in my app I suddenly get this message: enter image description here

It happend once, then I opened another DB and now it happend again... On my computer when I run the app it works just fine Help?

MySQL shuts down connections after they've been unused for a while; the amount of time it waits depends on your MySQL server's settings. Often when you install it on your own machine, you'll wind up with a very long setting (which is good when you're doing development) but on a live system like PythonAnywhere it's generally shorter, to stop programs that don't close connections properly from locking up the server. Specifically, we have it set to five minutes.

To manage this, code should normally close connections when it's no longer using them. This can be a bit messy to code, but if you're using Flask, SQLAlchemy is a great library that handles all of this stuff for you. This blog post is a tutorial on building a DB-backed Flask app that uses SQLAlchemy, so you can probably take the code you need from there.

Great, thank you very much I have 2 more questions.. 1. How can I "revive" the DB? 2. And if I want to erase DB how can I do it?

  1. to revive the DB, just close the connection you're using and open a new one. It's just the specific database connection that had been closed, not the database itself (the error message is a little misleading). SQLAlchemy handles all of that for you, though, so you don't need to close connections -- you just ask it to give you one, and if it has a working open one it will return it, otherwise it will close any broken ones and create a new one for you.
  2. that depends on whether you want to delete the database entirely (eg. destroy all of the table schemas so that you can re-create them) or just delete the data. In the first case, you can use the DROP DATABASE command from a MySQL console. In the latter you'll need to run DELETE commands for each of your tables.

Hi all, we now have a help page on managing mysql connections, which includes info on the mysql server has gone away error 2006