Search code examples
pythonflaskmysql-pythonexecute

Flask mySQLDB execute success or failure


I am new to Python-Flask and am trying to use MySQLDB to conenct to the database. However, I am unable to determine how to check if the query executed by the cursor is successful or if it failed. In the code below, can someone please advise how I can go about the condition in the if statement? c is a cursor to a database and it is connecting successfully, so I excluded it from the code below.

qry = "SELECT count(*) FROM users where username = (%s)" % (username)
try:
    x = c.execute(qry) #Is this correct? Doe execute command return a value?
    if <<*Check if the query executed successfully*>>:
        return 'Success'
    else:
        return 'Failure'
except Exception as e:
    return 'Failure'

Solution

  • c.execute(qry) in your case won't return anything. So, You can't use it for if statement.

    However, You could use fetchall() or fetchone() to check if there are some results for your query. It would look something like this:

    qry = "SELECT count(*) FROM users where username = (%s)" % (username)
    try:
        c.execute(qry) #Is this correct? Doe execute command return a value?
        user = c.fetchone()
        if user:
            return 'Success'
        else:
            return 'Failure'
    except Exception as e:
        return 'Failure'