To delete a row and re-read the update data from Postgresql in Streamlit

Hello! I’m assuming you want to automatically reload and display the updated table in a Streamlit web application after deleting a row in a PostgreSQL database. Here’s how you can achieve this:

import streamlit as st
import psycopg2
import pandas as pd

# Connect to the database
connection = psycopg2.connect(
    host="your_host",
    user="your_username",
    password="your_password",
    database="your_database"
)

# Function to delete a row and update the displayed table
def delete_and_refresh_data(row_id):
    cursor = connection.cursor()

    # Define the SQL query to delete the row
    delete_query = f"DELETE FROM your_table WHERE id = {row_id}"

    # Execute the delete query
    cursor.execute(delete_query)
    connection.commit()

    # Fetch updated data
    cursor.execute("SELECT * FROM your_table")
    updated_data = cursor.fetchall()

    cursor.close()

    # Display the updated data in a Streamlit table
    st.write(pd.DataFrame(updated_data, columns=["Column1", "Column2", ...]))

st.title("Data Table")

# Fetch and display initial data
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table")
initial_data = cursor.fetchall()
cursor.close()

st.write(pd.DataFrame(initial_data, columns=["Column1", "Column2", ...]))

# Get user input for row deletion
row_id_to_delete = st.number_input("Enter the ID of the row to delete:")
if st.button("Delete"):
    delete_and_refresh_data(row_id_to_delete)

# Close the database connection
connection.close()

Hope this helps!

1 Like