【问题标题】:sqlite3 selecting values based on python variablessqlite3根据python变量选择值
【发布时间】:2018-01-04 10:22:15
【问题描述】:

我正在尝试根据用户通过 Tkinter 输入的变量从我的 python SQL 表中选择一个值。我的数据库有一个名为 employee_username 的列,并且在 1 行中有员工的用户名和密码。用户名由用户在 tkinter 窗口中输入

我的代码如下所示:

import sqlite3
import password_database
import tkinter

conn = sqlite3.connect('passwordDb.db')
c = conn.cursor()
username=entry_user.get()
password=entry_user.get()
database_username=c.execute(SELECT * FROM passwordDb WHERE 
employee_username=username)

if database_username!=' ':
   print('you entered a username which is not in the database')
else:
   running=True

当我运行此代码时,我无法获得任何结果。如何检查用户输入的值是否在我的数据库中,以及如何检索附加到用户名的员工密码。 在此先感谢

【问题讨论】:

  • 您是否收到错误消息?始终将完整的错误消息(Traceback)放在问题中(作为文本,而不是屏幕截图)。还有其他有用的信息。
  • 查询应该在" " - execute("SELECT * FROM passwordDb WHERE employee_username=?", (username, ))
  • 请注意,get 是一次获取条目小部件中的字符串。 usernamepassword 不会自同步。每次需要处理时,您都需要致电get

标签: database python-3.x tkinter sqlite


【解决方案1】:

您的代码不完整,但我想我理解您。

在查询数据库之前,您需要从用户名或输入中去除空格

username = input("username")
db_username = username.strip() #this removes the white space

# you can then check to see if the username is none...

records = cur.fetchall(); # this would return all matching records, loop through

if not database_user is None:
    ...
else:
    print("your username is bad") 

【讨论】:

    【解决方案2】:

    我看到一些错误

    首先:查询应该是字符串,它应该有?username应该是元组(username, )作为参数

    c.execute("SELECT * FROM passwordDb WHERE employee_username=?", (username, ))
    

    第二:您必须使用fetchall() 或 fetchone()` 来获取结果列表或第一个结果。

    rows = cur.fetchall()
    
    row = cur.fetchone()
    

    第三:execute() 不必返回值,因此与字符串" " 进行比较是没有意义的。 fetchall()/fetchone()` 返回行和结果,所以你可以检查它返回了多少行。

    rows = cur.fetchall()
    
    if len(rows) != 1:
       print("your username is bad or duplicate") 
    

    rows = cur.fetchall()
    
    if cur.rowcount != 1:
       print("your username is bad or duplicate") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2019-08-18
      • 2019-04-01
      • 2021-05-04
      • 2013-02-11
      相关资源
      最近更新 更多