I’m trying to create a function that gets a year from the user and searches a MySQL database for countries. But when I run this in my Python environment, it keeps giving me errors and I can’t figure out what’s wrong.
def get_country_data():
year_input = int(input("Please enter a year: "))
if not database_conn:
establish_connection()
sql_query = "SELECT * from nations WHERE independence_year = ?"
with database_conn:
db_cursor = database_conn.cursor()
db_cursor.execute(sql_query, (year_input,))
results = db_cursor.fetchall()
print(results)
Can someone help me understand what might be causing the issue? I’m pretty new to working with databases in Python and not sure if I’m handling the user input correctly or if there’s something wrong with my SQL syntax.
The problem is you’re checking if not database_conn when the variable doesn’t exist yet - that throws a NameError instead of returning False. I hit this exact issue when I started doing database stuff. Just initialize database_conn = None at the module level or catch the exception properly. Also double-check that your establish_connection() function actually assigns to the global variable. I’d throw the whole thing in a try-except block for connection errors - MySQL connections fail silently sometimes and you won’t know why without proper error handling.
You’re using SQLite placeholder syntax, but you need MySQL syntax. MySQL uses %s instead of ? for parameters:
sql_query = "SELECT * from nations WHERE independence_year = %s"
I’d also add error handling around your database operations - connection issues happen all the time. I made this exact mistake switching from SQLite to MySQL and spent hours debugging before I figured out it was just the placeholder syntax. Your code structure looks good otherwise, this one character change should fix it.
you’re missing the mysql connector import, and your connection might not be set up right. also check that your table is actually named “nations” in the database. I’ve run into this same thing when the table didn’t exist or the connection failed without throwing an error.
Your int(input()) will crash if someone enters non-numeric data. Learned this the hard way when users typed “1776” with quotes or hit letters by mistake. Wrap it in try-except to catch ValueError exceptions. Also check that your database_conn variable is accessible in the function - if it’s defined elsewhere you’ll need to declare it global inside the function. MySQL connector can be picky about cursor management, so I’d explicitly call cursor.close() after fetching results even with the context manager.