将 SQLite 数据库中的列转换为单元格值

Converting columns in SQLite database to cell values

假设我有以下数据库结构:

fruits vegetables grains
banana carrot wheat
apple broccoli barley
watermelon cabbage malt
strawberry tomato semolina

我希望它更容易使用,将其转换为以下结构:

name type
banana fruit
apple fruit
broccoli vegetable
barley grain
tomato vegatable
wheat grain

我将如何编写一个 python 程序来为我做这件事?

我发现此解决方案是可行的 - 但可能不如 pythonic/readable 应有的那样:

import sqlite3

def transform():
    con = sqlite3.connect('database.db')
    cur = con.cursor()
    cur2 = con.cursor()
    cur3 = con.cursor()
    data = cur.execute('''SELECT * FROM table_1''')
    columns = []
    for column in data.description:
        columns.append(column[0])
    for columnx in columns:
        cur2.execute(f'''SELECT {columnx} FROM table_1''')
        content = cur2.fetchall()
        for word in content:
            word = str(word)
            word = word.strip("(),' ")
            if word != "None":
               cur3.execute(f'''INSERT INTO table_1_V2 (column1, column2) VALUES (?,?);''',(str(word),str(columnx)))
    con.commit()

下面的程序可以完成这项工作 - 虽然它可能会多一些 pythonic/readable:

import sqlite3

def transform():
    con = sqlite3.connect('database.db')
    cur = con.cursor()
    cur2 = con.cursor()
    cur3 = con.cursor()
    data = cur.execute('''SELECT * FROM table_1''')
    columns = []
    for column in data.description:
        columns.append(column[0])
    for columnx in columns:
        cur2.execute(f'''SELECT {columnx} FROM table_1''')
        content = cur2.fetchall()
        for word in content:
            word = str(word)
            word = word.strip("(),' ")
            if word != "None":
               cur3.execute(f'''INSERT INTO table_1_V2 (column1, column2) VALUES (?,?);''',(str(word),str(columnx)))
    con.commit()

在这里的 INSERT 语句中,column1、column2 可以扩展为您想要填充的新列的数量 table,要插入新列的值位于语句结束(此处为 word 和 columnx)。请注意,您必须实际创建具有所需内容的新 table 才能使此代码正常工作。