File size: 1,559 Bytes
327ffd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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()