At the moment, I have a database which contains username, password, etc.
I am wishing to look into the database to check if duplicates are in there.
con = lite.connect('userInfo.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM Users WHERE LOWER(Username) = LOWER(?)", (newID,))
rows = cur.fetchall()
if len(rows)!=0:
return "Duplicate detected"
Here is my code at the moment. newID is a new name and I wish to check if there are any existing entries in the database with the same name.
My question is – is the way I am doing it in my code a good idea? I’m mainly concerned with my approach. Should I be using something other than fetchall() ?
Thank you for your time! 🙂
P.S. This is for a website application.
Here’s a way to do exactly what you asked for – find out if a given
usernamealready exists:Since all you want is a
COUNTthis is adequate.Really, though, you shouldn’t be enforcing the uniqueness of the usernames yourself. Let the database do that for you by specifying the field to be either
UNIQUEorPRIMARY KEY.If you try to insert
"Alice", "alice@wonderland.com"after creating the database like above, this will get you an sqlite3.IntegrityError:To detect this, try to run the
INSERTand detect whether it fails.Incidentally, be very careful with using the upper/lowercase functions. Does
"Главное в новостях".lower()mean what you think it means?Since you mention this is for a webapp, I’ll just remind you to store your passwords as salted hashes of the password, using unique salts for each user (never as plain text!), and to guard against SQL injection by using the
(?,?,?,?,...)placeholders for SQL queries, not the(%s,%s) % (var1, var2)string interpolation method.To quote the sqlite3 documentation:
If you don’t do this, then someone could request the username
Robert Menzies; DROP TABLE users;with hilarious results.