[英]Mysql - Comparing query result with String in Python
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 由于电子邮件字段为空,因此应返回1
result: (u'',) OK
length of result: 1
email taken
result: 0
Any advice? 有什么建议吗?
result_set is an array, which you access the first tuple: result_set[0]
=> (u'',)
which indeed has a length of 1. result_set是一个数组,您可以访问第一个元组: result_set[0]
=> (u'',)
,其长度实际上为1。
Accessing the first element (such as via result_set[0][0]
) would give you the empty string you're actually looking for. 访问第一个元素(例如,通过result_set[0][0]
)将为您提供您实际上正在寻找的空字符串。
.fetchall()
returns a list of tuples. .fetchall()
返回一个元组列表。 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()
: 或更简单地使用.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: 另外,您应该像这样查询数据库,以避免发生SQL注入攻击:
query = "select email from u_code where code = %s"
cursor.execute(query,(code,))
For checking an existing value in table, i would recommend COUNT query 为了检查表中的现有值,我建议使用COUNT个查询
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.