gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:30:39 25 4
gpt4 key购买 nike

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

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 语法错误。我尝试使用“'”“'”左括号和右括号来转义它们,但它不起作用并且使网页崩溃。

最佳答案

你想要:

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

但会查看应该工作的 .fetchone(),以及 SQL 中的 EXISTS(因此它应该具有唯一约束并让 DB 解决)并返回一个 bool 型的空结果。

关于python - 使用python检查MySQLdb中是否已经存在电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13687707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com