【问题标题】:How to use flask variable in calling SELECT query in MariaDB如何在 MariaDB 中调用 SELECT 查询时使用烧瓶变量
【发布时间】:2021-12-28 16:22:27
【问题描述】:

从注册表单中调用 MariaDB 中的 SELECT 查询的正确语法是什么。 具体来说,在 WHERE 子句中。我一直在网上寻找调试它,它似乎不起作用(语义上)。

这是我的 python 烧瓶中的代码。

@app.route('/check_email', methods = ['POST', 'GET'])
def chck_Email():
  if request.method == 'POST':
    visEmail = request.form['email']
    conn = mariadb.connect(**config)
    print(f"WE ARE CONNECTED ORAYT")
    # create a connection cursor
    cur = conn.cursor()
    # execute an SQL statement
    try:
        print(visEmail)
        #sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name)  VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
        current_Email= cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
        
        print(current_Email)
        if current_Email != None:
            print('Email Invalid: Email already exists!')
            form = Registration_Form()
            exists = {
                "email_exists": True
            }
            return render_template(exists,'register.html', form = form )

""visEmail 是一个变量,它应该保存用户在单击提交时提供的电子邮件地址,然后程序会检查数据库中给定的电子邮件地址是否已经存在于数据库中。

我打印了 visEmail 变量中的数据以查看字符串(这很好),但数据库中的执行返回“无”(它不应该返回无,因为我已经有给定的电子邮件地址数据库)。它应该返回错误“电子邮件已经存在”

非常感谢

【问题讨论】:

  • 您忘记调用cur.fetchone() 来获取结果行。
  • 无论如何我都不能调用 cur.fetchone(),因为它会给我一个关于“Nonetype”的错误,因为 cur.execute() 返回一个 None :(
  • 嗯? cur.execute() 不返回任何内容,您认为这有什么意义?
  • 因为 "current_Email" 变量将用于检查此类电子邮件是否存在(在其下方的 IF 语句中)
  • 但是您应该使用cur.fetchone() 设置current_Email,而不是cur.execute()。看我的回答

标签: python flask select mariadb where-clause


【解决方案1】:

您没有获取结果行。 cur.execute() 不返回任何内容,您必须调用 cur.fetchone() 以获取结果,并将其分配给 current_Email

    try:
        print(visEmail)
        #sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name)  VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
        cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
        current_Email = cur.fetchone()
        
        print(current_Email)
        if current_Email != None:
            print('Email Invalid: Email already exists!')
            form = Registration_Form()
            exists = {
                "email_exists": True
            }
            return render_template(exists,'register.html', form = form )

【讨论】:

  • 兄弟,它似乎有效!我得到了它应该发送的错误。所以应该将 cur.fetchone() 分配给变量?不是 cur.execute()。这也许就是为什么当我在其上调用 cur.fetchone() 时我在“current_Email”变量上得到 None 结果的原因。
猜你喜欢
  • 1970-01-01
  • 2022-10-13
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多