tirupats
tirupats

Reputation: 238

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'

Upvotes: 3

Views: 2114

Answers (2)

Fejs
Fejs

Reputation: 2888

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'

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 600059

You already have the means for detecting the failure in the code you have posted. If something goes wrong with the query, Python will raise an exception, which you can catch. Although it's worth noting that you should never catch a bare Exception, and you should certainly never hide what that exception is; catch the relevant MySQLdb exceptions, eg MySQLdb.Error.

Upvotes: 0

Related Questions