繁体   English   中英

Python SQLite3 If字段==变量

[英]Python SQLite3 If field == variable

我已经看到了很多线程来检查该字段是否存在,但是我有点困惑,我想知道是否有人可以告诉我hwot检查它是否存在,并查看它是否等于一个变量输入。

到目前为止我的代码

import sqlite3
import datetime
import smtplib

now = datetime.datetime.now()
conn = sqlite3.connect("accounts.db")

c = conn.cursor()



def register():
    username = input("Username: ")
    password = input ("Password: ")
    date = now.strftime("%d-%m-%Y %H-%M")
    adminlevel = 0

    c.execute("""INSERT INTO accounts
              (username,password,date,adminlevel)
              VALUES(?,?,?,?)""",(username,password,date,adminlevel))
    conn.commit()

    print("You have succesfully registered at " + date, "An email has been sent to you with your information!")
    menu()

from getpass import getpass

def login():
    def loggedin():

        if adminlevel > 0:
            print("Hello There Admin!")
            print("Commands: ")
        else:
            print("Hello there {}".format(username))
            print("Commands: Name, Date, Friend, Logout")





    adminlevel = 0
    username = input("Please enter your username: ")
    password = getpass("Please enter your password: ")
    admin = c.execute("select 1 from accounts where adminlevel > 0")
    c.execute("select 1 from accounts where username = ? and password = ?", (username, password))
    if c.fetchone():
        print('Hello there! {}'.format(username))
        loggedin()
    else:

        print("Username and Password Not Found!")
        login()

def menu():
    print("="*40)
    print("Login & Registration System")
    print("="*40)

    choice = input("Login or Register? ")

    if choice == "register":
        register()
    elif choice == "login":
        login()


menu()

假设您要在login()函数中检查用户的凭据,可以对此执行SELECT查询:

from getpass import getpass

def login():
    username = input("Please enter your username: ")
    password = getpass("Please enter your password: ")
    c.execute("select 1 from accounts where username = ? and password = ?", (username, password))
    if c.fetchone():
        print('logged in: {}'.format(username))
    else:
        print("ERROR")

此代码提示用户输入用户名和密码(不回显到终端),然后使用这些值在数据库中查询account表中的匹配记录。 如果有记录,则fetchone()将返回1然后可以登录用户,否则用户名和/或密码不正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM