Locally running a MySQL db.
Streamlit 1.32 and Python 3.9.6.
ERROR:Getting a query() takes 2 positional args. but 3 were given when trying to write to the database.
query() method is expected to called once but for some reason it does it 3 times. Check out the following and give me suggestions on how to sort this weird prob. Thanks.
# test_mysql_connection.py
import logging
# Configure logging
logging.basicConfig(filename='app.log', level=logging.ERROR)
import streamlit as st
def test_mysql_connection():
try:
# Initialize connection using the secrets.toml configuration
conn = st.connection('mysql', type='sql')
# Perform a simple query to test the connection
query = 'SELECT 1'
result = conn.query(query)
# Check if the query result is as expected
if result.iloc[0][0] == 1:
print("MySQL connection test successful!")
else:
print("MySQL connection test failed. Unexpected query result.")
except Exception as e:
print(f"MySQL connection test failed. Error: {str(e)}")
# Function to retrieve data from the polls table
def get_polls_data():
try:
conn = st.connection('mysql', type='sql')
query = 'SELECT * FROM polls'
result = conn.query(query)
return result
except Exception as e:
print(f"Failed to retrieve polls data. Error: {str(e)}")
return None
# def get_users_data():
# try:
# conn = st.connection('mysql', type='sql')
# query = 'SELECT * FROM users'
# result = conn.query(query)
# return result
# except Exception as e:
# print(f"Failed to retrieve users data. Error: {str(e)}")
# return None
def create_poll():
st.subheader("Create New Poll")
title = st.text_input("Poll Title")
description = st.text_area("Poll Description")
start_date = st.date_input("Start Date")
end_date = st.date_input("End Date")
quest_type = st.selectbox("Question Type", ["Single Choice", "Multiple Choice"])
if st.button("Create Poll"):
if title and description and start_date and end_date and quest_type:
try:
conn = st.connection('mysql', type='sql')
# Convert the date format from "YYYY/MM/DD" to "YYYY-MM-DD"
start_date_formatted = start_date.strftime("%Y-%m-%d")
end_date_formatted = end_date.strftime("%Y-%m-%d")
# insert the poll question into the polls table
query = """
INSERT INTO polls (title, description, start_date, end_date, quest_type)
VALUES (%s, %s, %s, %s, %s)
"""
params = (title, description, start_date_formatted, end_date_formatted, quest_type)
conn.query(query, params)
# Get the ID of the newly inserted poll
query = 'SELECT LAST_INSERT_ID()'
poll_id = conn.query(query).iloc[0][0]
st.success("Poll created successfully!")
except Exception as e:
logging.error(f"Failed to create a poll. Error: {str(e)}")
st.error("Failed to create poll. Error: {str(e)}")
else:
st.warning("Please enter a question.")
# Streamlit app
def main():
st.title("Dashboard")
polls_data = get_polls_data()
# users_data = get_users_data()
if polls_data is not None and not polls_data.empty:
st.subheader("Polls")
# Display the table
st.dataframe(polls_data)
else:
st.warning("No polls data available.")
# if users_data is not None and not users_data.empty:
# st.subheader("Users")
# # Display the users table
# st.dataframe(users_data)
# else:
# st.warning("No users data available.")
if __name__ == '__main__':
test_mysql_connection()
main()
create_poll()