【发布时间】:2017-10-26 09:47:28
【问题描述】:
伙计们,我正在使用带有 python tkinter 作为前端的 sqlite3。该数据库是一个简单的数据库,有两个字段,username 和 password。我想做一个注册注册页面。其中两个字段中给出的数据将存储在 sqlite3 数据库中。数据插入正确。但是当提供的用户名已经存在于数据库中时,我想显示一个消息框。我尝试了下面的代码。
我的密码:
def signup():
userID = username.get()
passwd = password.get()
conn = sqlite3.connect('test.db')
c = conn.cursor()
result = c.execute("SELECT * FROM userstable")
for i in result:
if i[0] == userID:
messagebox.showerror("DUPLICATE", "USER ALREADY EXISTS!")
else:
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("INSERT INTO userstable VALUES (?, ?)", (userID, passwd))
conn.commit()
c.close()
conn.close()
username.delete(0,END)
password.delete(0,END)
username.focus()
messagebox.showinfo("SUCCESS", "USER CREATED SUCCESSFULLY")
这可行,但在出现错误消息后仍会存储重复的数据。如果用户名已经可用,我的要求是抛出错误并停止执行。如果用户名不可用,则应插入数据。
我哪里出错了?有人可以通过指出来解释我还是有其他方法可以实现这一点?看来我需要对我的功能进行一些修改。请指导我。
编辑 1
如果我尝试使用三个条件,则中断不起作用。
我的代码
def data_entry():
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS userstable(username TEXT, password TEXT)')
username = uname.get()
password = passwd.get()
result = c.execute("SELECT * FROM userstable")
if username != '' or password != '':
for i in result:
if i[0] == username:
tkinter.messagebox.showerror("DUPLICATE", "USER ALREADY EXISTS!")
break
else:
c.execute('INSERT INTO userstable (username, password) VALUES(?, ?)',(username,password))
conn.commit()
c.close()
conn.close()
another_clear()
tkinter.messagebox.showinfo("Success", "User Created Successfully,\nPlease restart application.")
else:
tkinter.messagebox.showerror("ERROR", "Fill both fields!")
【问题讨论】:
-
你知道这仍然不会阻止插入重复的用户名,对吧?仍然存在竞争条件(更不用说您必须在其他任何可能添加用户的小型维护工具或页面中重新实现该逻辑),您真的应该改用R. Scott's approach。