SQL Connection not available..Connecting to MySQL from streamlit

Hi,

From my streamlit UI application, Im trying to connect to MYSql database. Below is the code snippet for fetching the connection.

@st.cache(allow_output_mutation=True, hash_funcs={"_thread.RLock": lambda _: None})
def init_connection():
database = config[“database”]
return mysql.connector.connect(**config)

conn = init_connection()

Not sure what is the issue, but sometimes Im seeing SQL Connection not available. When I redeploy the application, able to get the connection.

Below is the code snippet how Im using this connection

def run_query():
with conn.cursor() as cur:
query = f"SELECT * FROM {database}.employee"
cur.execute(query)
return cur.fetchall()

Hey @lakshmi_mrudula,

First, welcome tot he Streamlit community! :partying_face: :partying_face: :tada: :tada: :star:

Actually @st.cache is being phased out and replaced with better alternatives. In this case, you’re connecting to a database and opening that connection only needs to happen one time so I would suggest using st.experimental_singleton. But you can find all the optimization options here:

Happy Streamlit-ing!
Marisa

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