【问题标题】:Checking if email already exists in MySQLdb utilizing python使用python检查MySQLdb中是否已经存在电子邮件
【发布时间】:2012-12-03 16:38:24
【问题描述】:

我的目标是检查 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 语法错误。我尝试使用 "'" "'" 左括号和右括号来转义它们,但它不起作用并导致网页崩溃。

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:

    你想要:

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

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

    【讨论】:

    • 我得到错误:builtin next = , cursor = , builtin None = None : Cursor object is not an iterator args = ('Cursor object is not an iterator',) message = 'Cursor object is not an iterator'
    • @MichaelRocca 哦 - 我忘了它是这样工作的 - 试试 fetchone 而不是光标对象
    • @JonClements:我更正了代码。我想你可能也想用一些关于准备好的陈述来填补答案。
    • @KeithGaughan 谢谢-但是,请随时提供您自己的答案-我正在回滚以使事情保持井井有条-无意冒犯(但您的编辑完全改变了我的初衷)
    • 没问题。我真的不想自己回答,因为除了获取整个结果之外,你的回答还不错。
    猜你喜欢
    • 2017-01-28
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2014-12-29
    • 2011-12-02
    • 2017-10-09
    • 2015-02-28
    • 2017-09-13
    相关资源
    最近更新 更多