【问题标题】:Python, Flask, MySQL - Check if email exists in databasePython,Flask,MySQL - 检查数据库中是否存在电子邮件
【发布时间】:2018-10-28 14:17:48
【问题描述】:

我对 SQL 很陌生,但我在学校项目中需要它。我正在尝试制作一个需要帐户的(python)网络应用程序。我可以将数据放入我的 SQL 数据库,但现在我需要一些方法来验证数据库中是否已经存在电子邮件(通过 html 表单输入)。可能是有史以来最简单的查询,但我对如何开始一无所知。 :(

如果这是一个重复的问题,我很抱歉,但我找不到任何可以满足我需要的东西。

【问题讨论】:

  • 你的数据库表中的列是什么?
  • - 数据库名称: Essentials - 表名:users - 列名:email
  • 你能写出你已有的代码吗? (读取用户的邮件,查询数据库?)
  • 我没有任何 python 代码读取数据,尽管读取电子邮件的 SQL 查询看起来像这样 SELECT email FROM essentials.users;
  • 如果您特别遇到 SQL 问题,请考虑使用 WHERE 子句(例如与 IF EXISTS 子句结合使用)。

标签: python mysql sql flask


【解决方案1】:

如果您在项目中使用 SQLAlchemy:

@app.route("/check_email")
def check_email():
    # get email from you form data
    email = request.form.get("email")

    # check if someone already register with the email
    user = Users.query.filter_by(email=email).first()
    if not user:
        # the email doesnt exist
        pass
    else:
        # the email exists
        pass

Users.query.filter_by(email=email).first() 等于 SQL:

SELECT * from users where email="EMAIL_FROM_FORM_DATA"

如果你使用pymsql(或类似的东西):

import pymsql

@app.route("/check_email")
def check_email():
    # get email from you form data
    email = request.form.get("email")

    conn = connect(host='localhost',port=3306,user='',password='',database='essentials')
    cs1 = conn.cursor()
    params = [email]
    # cursor return affected rows
    count = cs1.execute('select * from users where email=%s', params)  # prevent SqlInject

    if count == 0:
        # count 0 email
    else:
        # the email exists
        # and if you want to fetch the user's info
        user_info = cs1.fetchall()  # the user_info should be a tuple


    # close the connection
    cs1.close()
    conn.close() 

【讨论】:

  • 使用你的“攻击方式”;) 输出无计数。不管是什么电子邮件。
  • 你在使用pymysql吗?或其他mysql客户端?这些之间可能存在差异。顺便说一句,第一行应该是from pymysql import connect
  • 我使用 mysql-connector,但我使用简单的 INSERT IGNORE` 就让它工作了`
【解决方案2】:

我能够通过简单地使用来解决我的问题 INSERT IGNORE 之后是 checking if it was ignored with the primary key

感谢所有提供帮助的人!

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2014-03-15
    • 2014-05-10
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多