Colton Allen
Colton Allen

Reputation: 3060

Flask - Check database against string

Code:

userExists = g.db.execute('SELECT username FROM users WHERE username = ?', [request.form['usr']])

if request.form['usr'] == userExists:
    error = 'Username already exists.'

Hopefully the code is self-explanatory. If not, I want a registering user to have his name checked against the database. The username must be unique so if the information entered into the form (request.form['usr']) is equal to the result of the SQL query saved to the userExists variable then an error should be thrown (error = 'Username already exists.').

Is the query returning the number of rows matching username instead of the value of username? Or is the logic just incorrect.

Upvotes: 0

Views: 343

Answers (2)

Spade
Spade

Reputation: 2280

Assuming you are using sqlite3 as indicated by the use of g.db.execute and that you have maintained a unique index on the username column since when it was created you could do something like:

username = request.form['usr']
print "Attempting to insert username = %s" %username
try:
    g.db.execute("insert into users(username) values('%s')" %username)
except sqlite3.IntegrityError:
    print 'Username %s is already in database' %username
    g.db.rollback()
except:
    g.db.rollback()
    #Handle other errors as desired. 
finally:
    g.db.commit()

g.db.close()

Unfortunately, you cannot alter a table to add unique indices or primary keys. But if you are still in design, this should work.

Upvotes: 0

Liteye
Liteye

Reputation: 2801

You can do this by defining the username as an unique key when creating table. Then put the INSERT into a try ... catch ... block. If the username exists, an exception will be thrown.

Upvotes: 1

Related Questions