Spaces:
Sleeping
Sleeping
import gradio as gr | |
import sqlite3 | |
import pandas as pd | |
# Database file | |
db_file = "attendance_records.db" | |
# Helper Functions | |
def get_table_names(): | |
"""Retrieve the names of all tables in the database.""" | |
conn = sqlite3.connect(db_file) | |
cursor = conn.cursor() | |
cursor.execute(""" | |
SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'; | |
""") | |
tables = [row[0] for row in cursor.fetchall()] | |
conn.close() | |
return tables | |
def query_table(table_name): | |
"""Query the selected table and return its content as a DataFrame.""" | |
conn = sqlite3.connect(db_file) | |
try: | |
df = pd.read_sql_query(f"SELECT * FROM {table_name}", conn) | |
except Exception as e: | |
conn.close() | |
return str(e) | |
conn.close() | |
return df | |
def display_table(table_name): | |
"""Fetch and display the contents of the selected table.""" | |
df = query_table(table_name) | |
if isinstance(df, pd.DataFrame): | |
return df | |
else: | |
return f"Error fetching data: {df}" | |
# Gradio App | |
def create_gradio_app(): | |
with gr.Blocks() as app: | |
gr.Markdown("# Database Query Interface") | |
gr.Markdown("### Select a table to view its contents") | |
table_selector = gr.Dropdown(choices=get_table_names(), label="Select Table") | |
output = gr.Dataframe(label="Table Data", interactive=False) | |
table_selector.change( | |
fn=display_table, | |
inputs=table_selector, | |
outputs=output, | |
) | |
return app | |
app = create_gradio_app() | |
app.launch() | |