从SQLite表创建HTML表格

-1 投票
1 回答
4818 浏览
提问于 2025-04-17 21:24

我有一个名为“seinfeldFood.sqlite”的数据库,里面有四个表: “episodes”(剧集)、 “foods”(食物)、 “foods_episodes”(食物与剧集的关系)和 “food_types”(食物类型)。我想写一个程序,让用户可以从“seinfeldFood.sqlite”中选择一个表,然后把这个表的内容展示在一个HTML文件里。此外,HTML表格应该满足以下两个要求:1)标题要和表名一样,2)表格的列名要作为表头。

我写了以下代码,试图把sqlite表的内容添加到HTML文件中,但结果得到的是一个空白的HTML文件。

import webbrowser
import os
import sqlite3 as sqlite

def getTable(cursor):
    cursor.execute("""SELECT tbl_name FROM sqlite_master WHERE type = 'table'""")
    tables = [t[0] for t in cursor.fetchall()]
    print tables
    prompt = "Select table name from: %s\n"%" ".join(tables)
    while True:
        table = raw_input(prompt)
        if table in tables:
            return table

def createTable(cursor,tableName):
    category = []
    results = cursor.execute(("""SELECT * FROM %s""")%(tableName))
    for r in results:
        category.append(r[1])
    cursor.execute("CREATE TABLE IF NOT EXISTS Category (name)")
    cursor.execute("""INSERT INTO Category (name) VALUES (?)""",("Category",))
    for c in category:
        cursor.execute("""INSERT INTO Category (name) VALUES (?)""", (c,))
    #conn.commit()
    #result_new = cursor.execute("""SELECT * FROM Category""")
    #for t in result_new:
        #return t

def getHTML(cursor,tableName):
    html = \
        """<html>
        <head>
        <title>%s</title>
        <script>
        function createTable(%s,%s)
        {
        }
        </script>
        </head>
        </html>
        """%(tableName,cursor,tableName)
    return html    

def viewDatabase(dbname):
    fo = open(os.path.join(dataDir,"tableView.html"),"w")
    fo.write( getHTML(cursor,tablename,))
    fo.close()
    webbrowser.open_new(dbname)

测试我的函数(结果是空白的HTML文件):

connFood = sqlite.connect(os.path.join(dataDir,"seinfeldFood.sqlite"))
cursor = connFood.cursor()

tablename = getTable(cursor)
createTable(cursor,tablename)
getHTML(cursor, tablename,)
viewDatabase("Category")

这是表格的图片:

在这里输入图片描述

1 个回答

1

你似乎对一些基本概念有点困惑。

1) 如果你已经有了一个sqlite表,那就不需要写“CREATE TABLE IF NOT EXISTS”这个命令了。

2) 你想用javascript来填充一个HTML表格吗?

你用纯HTML写的表格代码大概是这样的:

html_part='<table>'
for t in result_new:
    html_part=html_part + '<tr><td>' + t + '</td></tr>'
html_part=html_part + '</table>

然后把这个html部分放到你生成的HTML文档的合适位置。

其实,使用一个网页框架会更简单。可以试试http://web2py.com

这样你就可以用一个智能网格来创建一个可编辑和可搜索的数据库表格了。

撰写回答