2010-10-17 60 views
1

我想生成一些簡單的HTML頁面,其中包含存儲在MySQL數據庫中的數據。我已經搜索並搜索了這個答案,雖然我可以從txt或用戶輸入成功生成html頁面,但我無法使用SQL進行操作。我不擔心格式化HTML或任何其他數據,我可以解決。我想要做的就像下面的內容,但是我不知道如何將數據打印到文件中。任何幫助將不勝感激。使用Python將MySQL數據作爲源文件寫入HTML文件?

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

更改此:

htmlFile.write = data 

到:

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

htmlFile.write(formatDataAsHtml(data())) 
+0

謝謝,但我得到一個錯誤說:類型錯誤:必須是字符串或只讀字符緩衝區,而不是元組 – 2010-10-17 02:34:37

+0

哎呀,忽視了,現在更新。 – 2010-10-17 02:47:28

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) 

如果您data()返回一個元組,你可能需要使用join,使之成爲一個字符串。

1

請務必將

fdsaasdfsdsdaasdfsdafsdfasfas ASF SA F SAA ASA