Python GUI中出现AttributeError: 'tuple' object has no attribute 'encode'报错求助
Let's break down exactly what's causing this error and how to fix it right away:
The Root Cause
Look at this line in your code:
sql = "SELECT * FROM farm_registration \ WHERE barangay = %s", (e_barangay);
You’re accidentally creating a tuple (a pair of values: your SQL string and the parameter) and storing it in the sql variable. When you pass this tuple directly to cur.execute(sql), the database driver tries to treat it like a regular SQL string and calls .encode() on it—but tuples don’t have this method, hence the error.
The Simple Fix
You need to pass your SQL string and parameters as separate arguments to the execute() method. Here are two clean ways to do it:
Recommended: Parameterized Query (Best for Security)
Keep your SQL as a standalone string, then pass the parameters as the second argument toexecute()—this also prevents SQL injection attacks:cur = conn.cursor() sql = "SELECT * FROM farm_registration WHERE barangay = %s" # Removed the unnecessary backslash cur.execute(sql, (e_barangay,)) # SQL string first, parameters second results = cur.rowcountString Formatting (Not Recommended for Production)
If you were trying to format the SQL string directly (note: this is risky for security), you’d use string formatting operators—but stick to the first method for production code:# For reference only, avoid in production sql = "SELECT * FROM farm_registration WHERE barangay = %s" % (e_barangay,) cur.execute(sql)
Quick Note
Always use parameterized queries (the first fix) whenever possible. They’re safer, cleaner, and avoid issues like the one you ran into here.
内容的提问来源于stack exchange,提问作者Anthony Mendoza

