Python和SQLite:检查数据库中是否存在项目?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python和SQLite:检查数据库中是否存在项目?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2208字,纯文字阅读大概需要4分钟。
内容图文
![Python和SQLite:检查数据库中是否存在项目?](/upload/InfoBanner/zyjiaocheng/898/852292750288414ba3f1745a011215d7.jpg)
我有一个方法,它将希望注册的用户的用户名和密码写入数据库.在存储他们提供给数据库的用户名和密码之前,我想检查他们选择的用户名是否已存在于“待处理”列表或已批准的“联系人”列表中.
这是我以前用来做的代码:
@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:检查数据库中是否存在项目?全部内容,希望文章能够帮你解决Python和SQLite:检查数据库中是否存在项目?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。