如何将字符串与数据库中的值匹配

How to match a string with a value in a database

我认为价值是正确的词。不对请编辑

内容:

问题 1(字符串未永久保留在数据库中)

问题2(问题1的思路)

我正在创建一个程序,它使用 Python3 中的 Sqlite3 将字符串添加到数据库中的 table 中。我正在使用一个要求您输入密码的功能。稍后,如果输入的字符串等于数据库中的某个内容,则想调用该函数。(如果它不等于数据库中的任何内容,则我们将其插入密码 table。)

问题一:

问题是,当我停止 运行 程序并再次 运行 时,该字符串不会保留在数据库中,这导致我可以重新输入以前的密码。我想要程序做的是让字符串在停止后保留在数据库中。
以上段落的程序如下:(向下滚动 以了解问题 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 的想法)

这是一个更新版本。我在这里所做的是尝试将字符串添加到数据库的 table 中,如果它与任何字符串匹配或不匹配。我在这里遇到的错误是 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()

对于 问题 1 将您的 db.commit() 移入循环,或者移入 try-exceptelse 或移入 [=16] =] 直接运行。

try:
  password()
except KeyboardInterrupt:
  print( "aborted" )
  break
except sqlite3.IntegrityError:
  print( "cannot reuse that password" )
else:
  db.commit()

def password():
  pwd = input( "password: " )
  sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest()
  cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, ))
  db.commit()

在插入成功后单独提交,否则您可能会因未处理的错误而丢失所有插入。除了未提交的插入之外,我没有看到您将密码设置为 "not stay in the database" 的任何其他原因。

至于问题2:当程序进入循环时,password()还没有被调用,所以pwd还不存在尝试使用它。

while True:
  #take pwd from password and put it here
  sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest()  # <-- pwd is undefined here ...
try:
    password()  # ... because it needs this to be executed at least once

为什么还要在循环中第二次执行 hashlib.sha256?您已经在 password 中完成了;您可以从循环中删除该行并立即删除 NameError 。此外,循环的 except 块中的第二个 INSERT 没有意义。如果 INSERT 违反了 UNIQUE 约束并引发了 IntegrityError,你会再次尝试同样的 INSERT 吗?这将引发相同的错误,这次未处理该错误并将使您的程序崩溃。

坚持你的第一种方法,它好多了。不要使用全局变量,除非你真的 真的 真的 必须。