Python requires the MySQLdb module. You can get it from the project’s web page at http://sourceforge.net/projects/mysql-python/ if you do not already have it. You can find out if you type “python” and then try to “import MySQLdb”. Python is case sensitive.
#!/usr/bin/python
import MySQLdb
class album:
def __init__(self, albumInfo):
self.album = albumInfo["album"]
self.artist = albumInfo["artist"]
self.year = albumInfo["year"]
self.rating = albumInfo["rating"]
def tableRow(self):
rowHTML = "<tr>"
for cell in [self.album, self.artist, self.year, self.rating]:
rowHTML += self.tableCell(cell)
rowHTML += "</tr>\n"
return rowHTML
def tableHeader(self):
rowHTML = "<tr>"
for header in ["Album", "Artist", "Year", "Rating"]:
rowHTML += self.tableCell(header, "th")
rowHTML += "</tr>\n"
return rowHTML
def tableCell(self, cellData, cellType="td"):
return "<" + cellType + ">" + str(cellData) + "</" + cellType + ">"
class albums:
def __init__(self, user, password, host="localhost"):
self.db = 'music'
self.query = 'SELECT album, artist, year, rating FROM albums ORDER BY artist'
self.sql = MySQLdb.connect(host=host, user=user, passwd=password, db=self.db)
self.cursor = self.sql.cursor(MySQLdb.cursors.DictCursor)
self.nextAlbum = None
def __destroy__(self):
if self.sql:
self.cursor.close()
self.sql.close()
def table(self):
if self.sql:
albums = None
try:
self.cursor.execute(self.query)
albums = self.cursor.fetchall()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
if albums:
tableRows = [album.tableHeaders()]
for albumInfo in albums:
currentAlbum = album(albumInfo)
tableRows.append(currentAlbum.tableRow())
table = "<table>\n"
table += "\n".join(tableRows)
table += "</table>\n"
else:
table = "<p>Unable to acquire albums</p>\n"
else:
table = "<p>Unable to connect to database " + self.db + ".</p>\n";
return table
def page(self):
page = "<html>\n"
page += "<head><title>My Albums</title></head>\n"
page += "<body>\n"
page += "<h1>My Albums</h1>\n"
page += self.table()
page += "</body>\n"
page += "</html>\n"
return page
albumList = albums('Username', 'Password')
print albumList.page()