使用python检查MySQLdb中是否已存在电子邮件

时间:2012-12-03 16:38:25

标签: python mysql mysql-python

我的目标是检查mysql数据库中是否已存在电子邮件。我将信息从webform(字符串)中提取到变量中。我目前有以下代码:

import MySQLdb

db = MySQLdb.connect("localhost","username","password","databasename")
cursor = db.cursor()
if cursor.execute("select count(*) from registrants where email = " + "'"emailvar"'") == 0:
    print "it doesn't exist"

当我尝试访问该页面时,我收到内部服务器错误。我将错误缩小到“'”emailvar“'”,代码工作正常,但电子邮件有“@”和“。”这会导致SQL语法错误。我尝试使用“'”“”开头和右括号来逃避它们,但它不起作用并使网页崩溃。

1 个答案:

答案 0 :(得分:2)

你想:

query = 'select count(*) from registrants where email=%s'
cursor.execute(query, emailvar)
if next(cursor, None) is None:
    # whatever

但是会看.fetchone()哪些应该有用,还有EXISTS在SQL中(它应该有一个唯一的约束并让DB解决它)并返回一个布尔式的空结果。

相关问题