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).
- mysql_db = MySQLDatabase('my_database')
- class BaseModel(Model):
- """A base model that will use our MySQL database"""
- class Meta:
- database = mysql_db
- class User(BaseModel):
- username = CharField()
- # 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.