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

时间:2022-09-25 23:55:52

My goal is to check if an e-mail already exists in the mysql database. I am pulling the information into the variable from a webform (string). I currently have the following code:

我的目标是检查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"

When I attempt to access the page I get an internal server error. I narrowed down the error to the "'"emailvar"'", and the code works fine, but e-mails have "@" and "." which cause SQL syntax errors. I attempt to escape them utilizing "'" "'" opening and closing parenthesis, but it does not work and crashes the web page.

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

1 个解决方案

#1


2  

You want:

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

But would look at .fetchone() which should work, and also EXISTS in SQL (whereby it should have a unique constraint and let the DB work it out) and return a boolean-esque empty result.

但是看看应该工作的.fetchone(),以及SQL中的EXISTS(它应该有一个唯一的约束并让数据库解决它)并返回一个布尔式的空结果。

#1


2  

You want:

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

But would look at .fetchone() which should work, and also EXISTS in SQL (whereby it should have a unique constraint and let the DB work it out) and return a boolean-esque empty result.

但是看看应该工作的.fetchone(),以及SQL中的EXISTS(它应该有一个唯一的约束并让数据库解决它)并返回一个布尔式的空结果。