我正在尝试从 sqlite3 数据库中获取数据,我知道该数据库使用 cursor.fetchone()
返回一个元组,但由于某种原因,当另一个程序上的用户(CGI 脚本)提交数据时,我将其放入并打印出来,2 匹配,就像他们的密码一样,所以当我尝试比较它们时,它们永远不会匹配:
#!/usr/bin/python
import sqlite3 as lite
import cgi
db = lite.connect('qwerty0987654321.db')
usrnme = "none"
passwd = "none"
passver = "none"
def main():
global usrnme
global passwd
print "Content-type:text/htmlrnrn"
print "<html>"
print "<head><title>Profile</title></head>"
print "<body>"
form = cgi.FieldStorage()
if form.getvalue('username'):
usrnme = form.getvalue('username')
if form.getvalue('passwd'):
passwd = form.getvalue('passwd')
if isauth() is True:
print "Welcome %s" % usrnme
elif isauth() is False:
print "Wrong username or password!"
else:
print "No Password!"
else:
print "No Username!"
print '</body>'
print '</html>'
def isauth():
global usrnme, passwd, passver
c = db.cursor()
c.execute("SELECT password FROM Users WHERE username = ?",(usrnme,))
passver = c.fetchone()[0]
passver = tuple(passver,)
passwd = tuple(passwd[0],)
if cmp(passwd,passver) == 0:
return True
else:
print(passver,passwd)
return False
if __name__ == '__main__':
main()
看起来你的错误在这里:passwd[0]
.因为 str 可以被索引,所以它会引用 str 中第一个位置的字符。那将是'n'
:
passver = c.fetchone()[0] # get the first field in the first item in the result set
passver = tuple(passver,) # add it to a tuple.
passwd = tuple(passwd[0],) # add passwd[0] (n) to a tuple
那行不通。请尝试:
passver = c.fetchone()[0] # get the first field in the first item in the result set
passver = tuple(passver,) # add it to a tuple.
passwd = tuple(passwd,) # add all of passwd to a tuple
# comparrison should succeed depending on contents of Users