用Python将MySQL数据写入HTML文件?
我正在尝试生成一些简单的HTML页面,这些页面里包含存储在MySQL数据库中的数据。我搜索了很多资料,虽然我能成功地从文本文件或用户输入生成HTML页面,但就是无法用SQL来实现。我并不担心如何把数据格式化成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()
3 个回答
-1
确保把
return ' '.join(result)
替换成
list_of_strings = ["(%s)" % c for c in result]
return ' '.join(list_of_strings)
2
把这个:
htmlFile.write = data
改成:
def formatDataAsHtml(data):
return "<br>".join(data)
htmlFile.write(formatDataAsHtml(data()))
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
把它变成一个字符串。