Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to build a Tkinter desktop app with Sqlalchemy as a database. If I read the SQLite database, and print both the header and content of database as show as below:

What I have tried:

<pre lang="SQL">
from sqlalchemy import text, create_engine

engine = create_engine("sqlite:///my_db.db")
my_conn = engine.connect()

with engine.connect() as my_conn:
    content  = my_conn.execute(text("SELECT * FROM student_address LIMIT 10"))

    header = [r for r in content.keys()]
    content = [list(r) for r in content] 
    
    value = [header, content]
    print(value)
    <pre>

The result:
[['id', 'name', 'class', 'mark', 'gender', 'hostel', 'address'],
[[1, 'Kelvin Loh', 'Six', 'Male', '45', '1', 'ffff\n']]] # 3D array instead of 2D array

but what I need:
[['id', 'name', 'class', 'mark', 'gender', 'hostel', 'address'],
[1, 'Kelvin Loh', 'Six', 'Male', '45', '1', 'ffff\n']]

I whant the value show in CTKtable value=value.

How could I fix it?
Posted

1 solution

This code should give you the desired output format. Now, you can use this value variable to display your data in a Tkinter GUI, such as with a CTKtable widget. You'll need to integrate it into your Tkinter application accordingly.

from sqlalchemy import create_engine, MetaData, Table

engine = create_engine("sqlite:///my_db.db")

# Reflect the table structure
metadata = MetaData()
metadata.reflect(bind=engine)

# Get the table object
table = Table('student_address', metadata, autoload=True, autoload_with=engine)

with engine.connect() as my_conn:
    # Fetch data from the table
    content = my_conn.execute(table.select().limit(10))

    # Extract column names
    header = content.keys()

    # Extract rows
    rows = [list(row) for row in content]

    # Combine header and rows
    value = [list(header)] + rows

print(value)
 
Share this answer
 
Comments
Member 15783420 26-Mar-24 23:58pm    
Yes it worked

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900