python - 使用 Python 写入以 MySQL 数据为源的 HTML 文件?

标签 python mysql html

我正在尝试生成一些简单的 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/

相关文章:

python - 从文本到字典,更新键值

python - 将 Pandas 数据框转换为字典并添加公共(public)键值对

python - 如何使用 PyOpenSSL 获取公钥?

Python:分割和分析字符串的最有效方法

MySQL:子选择未返回预期的 COUNT 结果

sql - MySQL:子查询中的总和值

java - 如何将 android 应用程序连接到非本地的 mysql 数据库?

html - Chrome devtools 的源选项卡中的 Emmet?

javascript - 分机JS : Image with dynamic height resizing container

jquery - 谷歌地图嵌入与粘性导航栏重叠