Text area is getting collapse when firing the query

i am using below code but when i am putting my query in st.text_area and hitting execute query then st.text_area is getting collapsed

if connection_status == "Connection successful":
    # Provide a text box for the user to enter a query
    query = st.text_area("Enter your SQL query:")

    result_container = st.empty()

    if st.button("Execute Query"):
        if query:
            try:
                # Execute the query and capture the results
                cursor = conn.cursor()
                cursor.execute(query)
                rows = cursor.fetchall()
                column_names = [column[0] for column in cursor.description]

                if not rows:
                    st.warning("No results found.")
                else:
                    result_df = pd.DataFrame(rows, columns=column_names)
                    result_container.subheader("Query Results")
                    result_container.dataframe(result_df)
                    with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as temp_file:
                        result_df.to_csv(temp_file.name, index=False)
                        result_container.markdown(
                            f"### [Download CSV](data:file/csv;base64,{temp_file})")
            except Exception as e:
                result_container.error(f"Error executing the query: {str(e)}")
        else:
            st.warning("Please enter a query.")

just to add, connection to DB is successfull, its just when i am putting the query in the the st.text_area and clicking on button Execute query, i am seeing no result and st.text_area is getting collapsed

Yup. Seems that it is a standard case of buttons not keeping state. Please refer to great video from @andfanilo

Thanks @TomJohn for the help, It worked.
just for completeness of this discussion i am adding the modified code below

if connection_status == "Connection successful":
    # Use st.session_state to maintain the state of the text_area
    if 'query' not in st.session_state:
        st.session_state.query = ""
    query1 = st.text_area("Enter your SQL query:", st.session_state.query)

    result_container = st.empty()

    if st.button("Execute Query") or st.session_state.execute_button_clicked:
        st.session_state.execute_button_clicked = True
        query = st.session_state.query 
        print(f"Query value: '{query1}'")
        if query1.strip():
            try:
                # Execute the query and capture the results
                cursor = conn.cursor()
                cursor.execute(query1)
                rows = cursor.fetchall()
                column_names = [column[0] for column in cursor.description]

                if not rows:
                    st.warning("No results found.")
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.