我正在尝试生成一些简单的 html 页面,其中包含存储在 MySQL 数据库中的数据。我已经搜索并搜索了这个问题的答案,虽然我可以从 txt 或用户输入成功生成 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()
最佳答案
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
将其变成一个字符串。
关于python - 使用 Python 写入以 MySQL 数据为源的 HTML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3951716/