gpt4 book ai didi

Python 和 SQLite : Check if an item exists in a database?

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:14 25 4
gpt4 key购买 nike

我有一种方法可以将希望注册的用户的用户名和密码写入数据库。在将他们提供的用户名和密码存储到数据库之前,我想检查他们选择的用户名是否已经存在于“待定”列表或已批准的“联系人”列表中。

这是我用来执行此操作的代码:

@cherrypy.expose
def writePending(self, username=None, password=None, message=None, signin=None):
""" Add request of friendship into a database which stores all
pending friendships.
"""

page = get_file(staticfolder + "/html/friendingPage.html")

if username != "" and password != "" and message !="":
con = lite.connect('static/database/Friendship.db')
cur = con.cursor()

with con:
cur.execute("CREATE TABLE IF NOT EXISTS pending(user TEXT, pass TEXT, info TEXT)")
cur.execute("CREATE TABLE IF NOT EXISTS contacts(user TEXT, pass TEXT)")

"Check to see if the username is already registered"

cur.execute("Select * from pending where user = ?", (username, ))
check1=cur.fetchone()
cur.execute("Select * from contacts where user = ?", (username, ))
check2=cur.fetchone()

if check1[0] != None:
page = page.replace("$Error", "The ID you used is still pending for friendship")
elif check2[0] != None:
page = page.replace("$Error", "The ID you used is already added as a contact")
else:
cur.execute("CREATE TABLE IF NOT EXISTS pending(user TEXT, pass TEXT, info TEXT)")
cur.execute("INSERT INTO pending VALUES(?, ?, ?)", (username, password, message))
page = get_file(staticfolder + "/html/thankYouPage.html")

else:
page = get_file(staticfolder + "/html/friendingPage.html")
page = page.replace("$Error", "You Must fill out all fields to proceed")

return page

但是,我会收到一条消息

Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "proj1base.py", line 540, in writePending
if type(check1[0]) != None:
TypeError: 'NoneType' object is not subscriptable

我想知道我能做些什么来避免这种情况?

谢谢。

最佳答案

在您的示例中,check1 将为None,因此您不能对其使用[0]。你可以这样做:

if check1 is not None:
(error response)

或者只是使用 cur.rowcount 而不是 cur.fetchone():

if cur.rowcount > 0:
(error response)

关于Python 和 SQLite : Check if an item exists in a database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9987262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com