Using MySQL

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

  1. mysql_db = MySQLDatabase('my_database')
  2.  
  3. class BaseModel(Model):
  4. """A base model that will use our MySQL database"""
  5. class Meta:
  6. database = mysql_db
  7.  
  8. class User(BaseModel):
  9. username = CharField()
  10. # 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 databaseconnections. What happens is your application starts, a connection is opened tohandle the first query that executes, and, since that connection is neverclosed, it remains open, waiting for more queries.

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

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