tags:

views:

79

answers:

2

Hi all,

I am trying to generate some simple html pages that contain data stored in a MySQL database. I have searched and searched for an answer to this and while I can successfully generate html pages from txt or user input I can't get it working with SQL. I am not worried about formatting the data in html or anything, that I can work out. All I would like to do is something like the following but I can't work out how to actually get the data printing to the file. Any help would be greatly appreciated.

import MySQLdb 

def data():    
    db_connection = MySQLdb.connect(host='localhost', user='root', passwd='') 
    cursor = db_connection.cursor()
    cursor.execute('USE inb104')
    cursor.execute("SELECT Value FROM popularity WHERE Category = 'movies'")
    result = cursor.fetchall()

    return result

htmlFilename = 'test.html'
htmlFile = open(htmlFilename, 'w')
htmlFile.write = data
htmlFile.close()
+2  A: 

Change this:

htmlFile.write = data

to:

def formatDataAsHtml(data):
    return "<br>".join(data)

htmlFile.write(formatDataAsHtml(data()))
Ned Batchelder
Thanks but I get an error saying: TypeError: must be string or read-only character buffer, not tuple
Mischa Colley
Oops, overlooked that, now updated.
Ned Batchelder
+2  A: 
def data():    
    db_connection = MySQLdb.connect(host='localhost', user='root', passwd='') 
    cursor = db_connection.cursor()
    cursor.execute('USE inb104')
    cursor.execute("SELECT Value FROM popularity WHERE Category = 'movies'")
    result = cursor.fetchall()

    return ' '.join(result)

If your data() returns a tuple, you may want to use join to make it into a string.

ghostdog74