【发布时间】:2019-03-14 20:18:57
【问题描述】:
我认为价值是正确的词。如果不是,请编辑。
内容:
问题 1(字符串未永久保留在数据库中)
问题 2(问题 1 的想法)
我正在创建一个程序,该程序使用 Python3 中的 Sqlite3 将字符串添加到数据库中的表中。我正在使用一个要求您输入密码的功能。稍后,如果输入的字符串等于数据库中的某个值,则想调用该函数。(如果它不等于数据库中的任何值,则将其插入密码表中。)
问题一:
问题是当我停止运行程序并再次运行它时,字符串不会留在数据库中,这导致它允许我重新输入以前的密码。我想要程序做的是让字符串在停止后留在数据库中。
这是上面段落的程序:(SCROLL DOWN for问题 1 )
import sqlite3
import hashlib
db = sqlite3.connect( "users.db" )
cur = db.cursor()
cur.execute( "CREATE TABLE IF NOT EXISTS passwords( pwd TEXT, UNIQUE( pwd ))" )
def password():
pwd = input( "password: " )
sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest()
cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, ))
while True:
try:
password()
#break
except KeyboardInterrupt:
print( "aborted" )
break
except sqlite3.IntegrityError:
print( "cannot reuse that password" )
db.commit()
db.close()
================================================ ======================== 问题 2:(问题 1 的想法)
这是一个更新的版本。我在这里所做的是尝试将字符串添加到数据库的表中,如果它与任何字符串匹配或不匹配。我在这里遇到的错误是 pwd 不是第 13 行的变量,尽管我确实将它作为一个变量并将其设置为全局变量。如果想帮助解决这个问题,我想知道为什么 pwd 不是变量以及如何使其成为变量。
import sqlite3
import hashlib
db = sqlite3.connect( "used_passwords.db" )
cur = db.cursor()
cur.execute( "CREATE TABLE IF NOT EXISTS passwords( pwd TEXT, UNIQUE( pwd ))" )
def password():
global pwd
pwd = input( "password: " ) #turn this into a global variable
sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest()
cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, ))
while True:
#take pwd from password and put it here
sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest()
try:
password()
#break
except KeyboardInterrupt:
print( "aborted" )
break
except sqlite3.IntegrityError:
print( "cannot reuse that password" )
cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, ))
db.commit()
db.close()
【问题讨论】:
标签: python database python-3.x sqlite passwords