注册时检查python中是否存在用户名

2024-10-01 15:28:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查用户名是否存在于表中。当我从表中选择所有内容时,代码正常工作,但当我仅尝试用户名时,出现错误。我得到的错误是

文件“\Python\Python37\lib\tkinter\uuuuu init\uuuuuuu.py”,第1705行,在调用中 返回self.func(*args)

文件/Calculator\u calorie/login\u register.py”,第89行,创建

login_backend.insert(self.namere_text.get(),self.passwordr1e_text.get())

文件\计算器\卡路里\登录\后端.py“,插入部分第18行

if cur.execute('SELECT name FROM user WHERE name = ?',(name)):

sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用1,提供了4个

import sqlite3
from tkinter import *
from tkinter import messagebox
from user import user

def connect():
    conn=sqlite3.connect("login.db")
    cur=conn.cursor()
    cur.execute("CREATE TABLE if NOT exists user(name text,password text)")
    conn.commit()
    conn.close()



def insert(name,password):
    conn=sqlite3.connect('login.db')
    cur = conn.cursor()
    if cur.execute('SELECT * FROM user WHERE name = ?', (name)):
        if cur.fetchone():
          messagebox.showinfo('Error', 'User already exist')
        else:
           cur.execute('INSERT INTO user VALUES(?,?)', (name, password))
           messagebox.showinfo('Register', 'Entry sucess')


    conn.commit()
    conn.close()




def create(self):
         if self.passwordr1e.get() != self.passwordr2e.get():
             messagebox.showinfo('error','Passwords do not match')
         elif len(self.namere.get()) == 0:
             messagebox.showinfo('error', 'Name field is empty')

         elif len(self.passwordr1e.get()) == 0:
               messagebox.showinfo('error', 'PASSWORD field is empty')

         else:
             login_backend.insert(self.namere_text.get(),self.passwordr1e_text.get())

Tags: textnameimportselfexecutegetiflogin
1条回答
网友
1楼 · 发布于 2024-10-01 15:28:58

As Michael commented,对于Python来说,要识别具有单个值的元组,它需要在末尾加一个逗号(name,)不是{}。见W3Schools Python Tuples

if cur.execute('SELECT name FROM user WHERE name = ?',(name,)):

注意,如果您只是检查一行是否存在,select 1可以节省一些时间


然而,有一种更安全、更快的方法可以做到这一点

As Chris commented,检查用户并插入是否包含race condition。如果两个进程试图同时创建同一个用户,它们都会认为该用户不存在,并且都会插入,从而导致重复

     Proc 1                                       Proc 2
t    SELECT * FROM user WHERE name = ?
i                                                 SELECT * FROM user WHERE name = ?
m    0 records found
e                                                 0 records found
|    INSERT INTO user VALUES(?,?)
v                                                 INSERT INTO user VALUES(?,?)

相反,设置一个unique constraint,执行insert,并捕获唯一错误

CREATE TABLE if NOT exists user(
  name text unique not null,
  password text not null
)

def insert(name,password):
    conn=sqlite3.connect('login.db')
    cur = conn.cursor()

    try:
        cur.execute('INSERT INTO user VALUES(?,?)', (name, password))
        messagebox.showinfo('Register', 'Entry sucess')
    except sqlite3.IntegrityError as e:
        if re.match(r'UNIQUE constraint failed', e.args[0]):
            messagebox.showinfo('Error', 'User already exist')
        else:
            raise e

    conn.commit()
    conn.close()

在单个查询中执行存在性检查和插入被称为“原子”,因为这两部分不能分开


注释

手工编写SQL有利于学习,但对于生产工作,请使用SQL Alchemy之类的框架

将密码存储为纯文本是不安全的Use a password hashing library such as bcrypt并阅读password hashing

为每个查询重新连接到数据库效率低下。连接一次并保持连接打开

相关问题 更多 >

    热门问题