Let's say I have the following database structure:
| fruits | vegetables | grains |
|---|---|---|
| banana | carrot | wheat |
| apple | broccoli | barley |
| watermelon | cabbage | malt |
| strawberry | tomato | semolina |
And I want it to be a bit easier to work with, transforming it into the following structure instead:
| name | type |
|---|---|
| banana | fruit |
| apple | fruit |
| broccoli | vegetable |
| barley | grain |
| tomato | vegatable |
| wheat | grain |
How would I go about writing a python program that could do this for me?
I found this solution to be workable - but maybe it's not as pythonic/readable as it should be:
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()