0

I would like to check whether the email returned by a query is empty. I am using the following code:

query = "select email from u_code where code = '"+code+"'"
cursor.execute(query)
result_set = cursor.fetchall()

length = cursor.rowcount
if (length==1):
   print ' result: ' + str(result_set[0]) + ' OK'
   print ' length of result: ' + str(len(result_set[0]))

   if (result_set[0] == ''):
       print("empty email")
       result = 1;
   else:
       print("email taken")
       result = 0


print "result: " + str(result)

The output is wrong. It should return 1 since the email field is empty

 result: (u'',) OK
 length of result: 1
 email taken
 result: 0

Any advice?

3 Answers 3

1

.fetchall() returns a list of tuples. So your condition will never be met.

You can either do:

if (result_set[0][0] == ''):
    print("empty email")
    result = 1;
else:
    print("email taken")
    result = 0

Or more simply use .fetchone():

result_set = cursor.fetchone()

if (result_set[0] == ''):
    print("empty email")
    result = 1;
else:
    print("email taken")
    result = 0

Also you should query your database like this to avoid the chance of SQL injection attacks:

query = "select email from u_code where code = %s"
cursor.execute(query,(code,))
Sign up to request clarification or add additional context in comments.

Comments

1

result_set is an array, which you access the first tuple: result_set[0] => (u'',) which indeed has a length of 1.

Accessing the first element (such as via result_set[0][0]) would give you the empty string you're actually looking for.

Comments

0

For checking an existing value in table, i would recommend COUNT query

query = "SELECT COUNT(email) FROM u_code WHERE code = %s"
cursor.execute(query, [code,])

# COUNT query always return value, if no matching data 
# it simply return integer value 0, so we can safely take data
# from result[0]
result_check = cursor.fetchone()

if not result_check[0]:
    print("empty email")
    result = 1;
else:
    print("email taken")
    result = 0

print "result: " + str(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.