Using MySQL

To connect to a MySQL database, we will use MySQLDatabase. After the database name, you can specify arbitrary connection parameters that will be passed back to the driver (either MySQLdb or pymysql).

  1. mysql_db = MySQLDatabase('my_database')
  2. class BaseModel(Model):
  3. """A base model that will use our MySQL database"""
  4. class Meta:
  5. database = mysql_db
  6. class User(BaseModel):
  7. username = CharField()
  8. # etc, etc

Error 2006: MySQL server has gone away

This particular error can occur when MySQL kills an idle database connection. This typically happens with web apps that do not explicitly manage database connections. What happens is your application starts, a connection is opened to handle the first query that executes, and, since that connection is never closed, it remains open, waiting for more queries.

To fix this, make sure you are explicitly connecting to the database when you need to execute queries, and close your connection when you are done. In a web-application, this typically means you will open a connection when a request comes in, and close the connection when you return a response.

See the Framework Integration section for examples of configuring common web frameworks to manage database connections.