want call the schema in sql in jupyter
To upload files, please first save the app
import streamlit as st
import pandas as pd
from sqlalchemy import create_engine, inspect
st.title("SQL Schema Explorer")
# Input for connection string
connection_string = st.text_input(
"Enter SQLAlchemy connection string:",
value="sqlite:///example.db",
help="Example: sqlite:///database.db, postgresql://user:password@localhost:5432/dbname"
)
if connection_string:
try:
# Create engine
engine = create_engine(connection_string)
# Get inspector
inspector = inspect(engine)
# Get all table names
tables = inspector.get_table_names()
if not tables:
st.warning("No tables found in the database.")
else:
st.success(f"Found {len(tables)} tables in the database.")
# Select table to inspect
selected_table = st.selectbox("Select a table to inspect:", tables)
if selected_table:
# Get columns information
columns = inspector.get_columns(selected_table)
# Create DataFrame for columns
df_columns = pd.DataFrame([{
'Column Name': col['name'],
'Type': str(col['type']),
'Nullable': col.get('nullable', True),
'Primary Key': col.get('primary_key', False),
'Default': str(col.get('default', ''))
} for col in columns])
st.subheader(f"Schema for table: {selected_table}")
st.table(df_columns)
# Get foreign keys
fks = inspector.get_foreign_keys(selected_table)
if fks:
st.subheader("Foreign Keys:")
for fk in fks:
st.write(f"- {', '.join(fk['constrained_columns'])} -> "
f"{fk['referred_table']}.{', '.join(fk['referred_columns'])}")
# Get indexes
indexes = inspector.get_indexes(selected_table)
if indexes:
st.subheader("Indexes:")
for idx in indexes:
st.write(f"- {idx['name']}: columns={', '.join(idx['column_names'])} "
f"(unique={idx['unique']})")
# Sample data preview
st.subheader("Sample Data Preview")
try:
sample_query = f"SELECT * FROM {selected_table} LIMIT 5"
sample_data = pd.read_sql(sample_query, engine)
st.dataframe(sample_data)
except Exception as e:
st.error(f"Could not fetch sample data: {str(e)}")
except Exception as e:
st.error(f"Error connecting to database: {str(e)}")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?