如何防止用户输入与另一用户相同的用户名或userID



我制作了一个注册系统,它接收用户的信息并将其存储在数据库中。我已经将userID和username作为主键,如何更改代码,使用户无法使用相同的用户名或userID注册。

def register_user():
userid_info = userid.get()
username_info = username.get()
password_info = password.get()
name_info = name.get()
phonenumber_info = phonenumber.get()
email_info = email.get()
region_info = region.get()
accesslevel_info = accesslevel.get()
# Sql code for writing the data that was written in the regsitering page. 
cursor = cnn.cursor()
query = "INSERT INTO `users`(`userID`, `userName`, `userPassword`, `name`, `phoneNum`, `email`, `region`, `accessLevel`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)"
query_vals = (userid_info, username_info, name_info, password_info, phonenumber_info, email_info, region_info, accesslevel_info)
cursor.execute(query, query_vals)
cnn.commit()
cursor.close()
cnn.close()
# removes the values in the entrys once the user selects that the registration was successful
userid_entry.delete(0, END)
username_entry.delete(0, END)
password_entry.delete(0, END)
name_entry.delete(0, END)
phonenumber_entry.delete(0, END)
email_entry.delete(0, END)
region_entry.delete(0, END)
accesslevel_entry.delete(0, END)
Label(screen1, text = "Registration successful", fg = "green", font = ("calibri", 11)).pack()

我会更改数据库,使主键仅为userID,然后使userName列成为唯一键。这样,既不能有重复的userId列,也不能有复制的userName列。正如你所拥有的,只有userId-userName组合必须是唯一的。然后修改代码以处理cursor.execute语句上可能出现的重复键异常(例如:IntegrityError:(1062,"键'PRIMARY'的重复条目'1'"((。如果确实出现异常,则可以查询数据库以确定哪一列或哪几列是重复的(如果异常消息中没有明确(。

您必须首先确保当前表具有唯一的userIduserName列。例如,

select count(distinct userId), count(distinct userName), count(*) from users;

这三个数字应该都一样。如果没有,你可以找到有问题的条目,例如:

select count(userId) as cnt, userId
group by userId
having cnt > 1;

如果存在具有相同用户名的用户,则可以在新注册发生时在数据库中进行搜索。只需从您的数据库中选择用户名等于新注册的用户名即可。

您可以创建一个存储所有id和密码的列表,每次有人输入新的id 时,程序都会检查列表中的一致名称

由于您已经将userID和username作为主键,因此可以使用异常来实现警告用户的逻辑。

edit:根据另一个答案的建议,请在数据库关系中只有一个主键。

try:
cursor.execute(query)
except IntegrityError:
# handle your exception here
return 

或使用MySQLdb错误

try:
cursor.execute(query)
except MySQLdb.Error as e:
# handle your exception here
return

您应该使用with来处理数据库事务,with处理关闭连接等,即使发生异常。

最新更新