3. How to connect a CherryPy server to a database

Many databases already have a corresponding Python module: Oracle, Sybase, MySql, PostgreSql, ...

Accessing these databases from a CherryPy server is really easy. All you have to do is use the initServer function to connect to the database.

For instance, you can connect to a MySql database using the following code (it uses the MySQLdb Python module):

import MySQLdb
def initServer():
    global dbConnection
    dbConnection=MySQLdb.connect(host, user, passwd, schema)
The following code is an example of running a query and using the result to build a page:
CherryClass Root:
view:
    def index(self):
        # Run the MySql query
        cursor=dbConnection.cursor()
        cursor.execute("select count(*) from user")
        result=cursor.fetchall()
        cursor.close()

        page="<html><body>"
        nbUser=result[0][0]
        page+="There are %s users in the database"%nbUser
        page+="</body></html>
        return page

This example can easily be adapted for any kind of database. Just find the appropriate Python module for the database and read its documentation.

See About this document... for information on suggesting changes.