簡體   English   中英

SQLite 3 / Python3.6-注冊和登錄腳本(sql和python的新功能)

[英]SQLite 3 / Python3.6 - Register and login script (New to sql and python)

我正在嘗試為python 3.6寫一個簡單的簡單登錄和注冊腳本。 但是,我無法擺脫此錯誤...每次注冊時,都沒有錯誤,但是當我再次運行它並使用相同的用戶名時,它不會顯示有關它已經存在的消息...我也無法使其輸出整個數據庫,所以我可以看到里面有什么(使用c.fetchall()

這是代碼...

import sqlite3 as sql, os

def dirCheck():

    exDir=False

    for count in os.listdir():
        if count == 'sql':
            exDir=True
    if exDir == False:
        os.mkdir('sql')



dirCheck()


cnct=sql.connect('./sql/usrAcc.db')
c=cnct.cursor()


def newTable():
    c.execute('CREATE TABLE IF NOT EXISTS users(username TEXT, password TEXT)')


newTable()

f=False
t=True
valid=f
taken=f





def credsWrite(username, password):
    c.execute('INSERT INTO users(username, password) VALUES (?, ?)',
              (username, password))
    cnct.commit()
    for row in c.fetchall():
        print(row)
    c.close
    cnct.close



def userReg():
    global valid, taken

    print(fancy[1])
    while not valid:
        print(fancy[3])
        username=str(input('>>  '))
        for row in c.fetchall():
            if str(username) == str(row[0]):
                print('Sorry, but that username has already been taken...\nPlease enter another\n>  ')
                taken=True
        if not taken:
            print(fancy[4])
            password=str(input('>>  '))
            valid=True
        credsWrite(username,password)

fancy=["""
 ================
| SQL LOGIN TEST |
 ================
 ""","""
 ==========
| REGISTER |
 ==========
 ""","""
 =======
| LOGIN |
 =======
 ""","""
 ================
| ENTER USERNAME |
 ================
 ""","""
 ================
| ENTER PASSWORD |
 ================
"""]


def startUp():
    print(fancy[0])
    chosen=False
    while not chosen:
        opt=int(input('\n Please choose one of the options below:\n\n-> Register for a new account [1]\n-> Login to an existing account [2]\n\nPlease type a number...\n\n>>  '))
        if opt==1:
            userReg()
            chosen=True
        elif opt==2:
            login()
            chosen=True
        else:
            print('\n\nPLEASE TYPE EITHER 1 OR 2...\n ')


if __name__ == "__main__":
    startUp()

您正在執行fetchall()而不實際執行任何代碼。

你在哪里

for row in c.fetchall():

您只瀏覽光標對象,而該對象尚未尋找任何東西。

要為此使用fetchall ,您需要添加SELECT語句。 例如,我通過添加一行並更改一行來更改您的代碼,然后它運行了(盡管還會出現另一種語法錯誤):

all_users = c.execute('SELECT * FROM users')
for row in all_users.fetchall():

(另一個語法錯誤是,無論用戶名是否有效,您都在嘗試編寫憑據。)


注意:您應該考慮的其他事項:

無需遍歷fetchall的結果,您可以搜索SQL中是否已經存在用戶名。 這也將使下一部分成為else

username=str(input('>>  '))
taken = c.execute('SELECT username FROM users WHERE username=?', (username,))
if taken:
    print('Sorry, but that username has already been taken...\nPlease enter another\n>  ')

(username,)是一個參數(在sqlite3python文檔中已進行了介紹 )。 使用用戶值時,應始終使用參數,以避免SQL注入 在圓括號中用逗號將其設為元組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM