Search code examples
pythonmysqlflaskflask-mysql

How do you check if a table contains data? (Python Flask MYSQL)


How exactly do you check if a table contains a specific value? For example,

if request.method == 'POST':
        email = request.form.get("email")
        cur = mysql.connection.cursor()
        cur.execute("SELECT * from login_info")
        data = cur.fetchall()    
        if email == data: # <--- I don''t know. This is what I want to know```

Solution

  • The data variable here will return a tuple from the cur.fetchall() function which will look something like this

    ((1,'random_email1@mail.com','First_name1','Last_name1'), 
     (2,'random_email2@mail.com','First_name2','Last_name2'),
     (3,'random_email3@mail.com','First_name3','Last_name3')...)
    

    If you need to find a row with a specific email address I suggest you do this for you SQL command

    email_query = "SELECT * FROM login_info WHERE email = %s"
    values = (email)
    cur.execute(email_query, values)
    data = cur.fetchone()
    #Assuming that there will be only one Row with the E-mail ID as the PRIMARY KEY
    

    The data tuple will then only contain a single row from the SQL table as follows (1,'random_email1@mail.com','First_name','Last_name')

    Here you can simply fetch the email address value by using data[1] which is where the email is in the tuple.