1

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()
0

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

Comments

2

Change this:

htmlFile.write = data

to:

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

htmlFile.write(formatDataAsHtml(data()))

1 Comment

Thanks but I get an error saying: TypeError: must be string or read-only character buffer, not tuple
-1

Make sure to replace

return ' '.join(result)

with

list_of_strings = ["(%s)" % c for c in result]
return ' '.join(list_of_strings)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.