Skip to content
Advertisement

How to use flask variable in calling SELECT query in MariaDB

What is the correct syntax for calling a SELECT query in MariaDB from a Registration Form. Specifically, in the WHERE clause. I’ve been looking all over the net to debug this and it does not seem to work (semantically).

Here is the code in my python flask.

@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 )

“”The visEmail is the variable that is supposed to be holding the email address given by the user upon clicking submit, the program then checks in the database if the given email address already exists in the DB.

I printed the data in the visEmail variable to see the string(Which is fine), but the execution in the database returns me with “None” (It should not be returning a None since I already have the given email address on the DB). It is supposed to return the error “Email Already exists”

THank you very much

Advertisement

Answer

You’re not fetching the row of results. cur.execute() doesn’t return anything, you have to call cur.fetchone() to get the results, and assign that to 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 )
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement