0

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

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

4

2 回答 2

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() 
于 2018-10-29T04:16:05.060 回答
0

我能够通过简单地使用 INSERT IGNORE检查它是否被主键忽略来解决我的问题。

感谢所有帮助过的人!

于 2018-10-29T12:14:41.137 回答