craisondigital craisondigital - 2 months ago 7
MySQL Question

Why is my Python Tuple only storing first value?

I am storing a mysql query w/in a tuple in my python script. I have a raw_input variable w/in the script which I would like to check if their is a match w/in the tuple.

curs.execute("""SELECT username, id FROM employees WHERE gid!=4""")
rows=curs.fetchall()
db.close()

uname = raw_input('Type the username for the new device: ')

for row in rows:
user = row[0]
empid = row[1]

if user == uname:
print 'User ' + uname + ' found...'
else:
print 'Not Found'


This only works if I type the username of the first employee. Any other employee returns 'Not Found'

I noticed that if I remove the raw_input line, and the if statement and add

for row in rows:
user = row[0]
empid = row[1]
print user


It prints all of the values

Answer

This may be a better approach based on what I assume you are trying to do.

There is no reason for the loop in Python to search for the user when you can simply add that to your WHERE clause.

# Get the username from input
uname = raw_input('Type the username for the new device: ')

# Check to see if username in table
curs.execute("SELECT username, id FROM employees WHERE gid != 4 AND LOWER(username) = %s", (uname.lower(),))
row = curs.fetchone() # If no records found, should return an empty tuple
db.close()

# Return the user if found
if row:
    user = row[0]
    empid = row[1]
    print 'User ' + user + ' found...'
else
    print 'Not Found'

This will return the username, if found. Otherwise 'Not Found'.