簡體   English   中英

為什么我在 sqlite 中收到 UNIQUE 約束錯誤?

[英]Why am I getting a UNIQUE constraint error in sqlite?

我正在嘗試創建一個銀行賬戶管理系統,用戶可以在其中創建賬戶、登錄並從該賬戶提取/存入資金。

# PHASE 1 (FILE I/O and Logic of System)
# Initialization of Current Balance ** Current Balance is the same for all users for the sake of simplicity ** 
myMoney = open("current_balance.txt")
currentBalance = int(myMoney.readline())

# Imports 
import sqlite3
# Creation of Bank Account and Notifying User(s) of Current Balance
class Bank_Account:
    def __init__(self):
        self.balance= currentBalance
        print("Welcome to Your Bank Account System!")
    # If statements for first screen
    def options_1(self):
        ch = int(input("1. Create an Account\n2. Log into Your Account\nEnter a Choice: "))
        if ch == 1: 
            self.create()
        if ch == 2: 
            self.Log_in()
    def options_2(self): 
        ch= int(input("1. Withdraw Money from Your Account\n2. Deposit Money to Your Account\nEnter a Choice: "))
        if ch == 1: 
            self.withdraw()
        if ch == 2: 
            self.deposit()
    # Function to Create an Account 
    def create(self): 
        user_create_input = str(input("Enter a Username:"))
        pin_create_input = int(input("Enter a Pin Number:" ))
        print("Account successfully created!")
     # Function to Log into Account 
    def Log_in(self):
        user_input = str(input("Enter your Username:"))
        pin_input = int(input("Enter your Pin Number:")) 
        print("Welcome", user_input, "!")
    # Function to Deposit Money 
    def deposit(self):
        amount=float(input("Enter the amount you want to deposit: "))
        self.balance += amount
        print("Amount Deposited: ",amount)
    # Function to Withdraw Money
    def withdraw(self):
        amount = float(input("Enter the amount you want to withdraw: "))
        if self.balance>=amount:
            self.balance-=amount
            print("You withdrew: ",amount)
        else:
            print("Insufficient balance ")

    def display(self):
        print("Net Available Balance=",self.balance)

# PHASE 2 (With Database) SQLite 3 

# Define Connection and Cursor 
connection = sqlite3.connect('Bank_Users.db')
cursor = connection.cursor()


# Create Users Table 
command1 = """ CREATE TABLE IF NOT EXISTS 
bank(pin INTEGER PRIMARY KEY, username text )"""
cursor.execute(command1)

# Add to Users/Bank
cursor.execute("INSERT INTO bank VALUES (7620, 'Kailas Kurup')")
cursor.execute("INSERT INTO bank VALUES (4638, 'Bethany Watkins')")
cursor.execute("INSERT INTO bank VALUES (3482, 'John Hammond')")
cursor.execute("INSERT INTO bank VALUES (3493, 'Melissa Rodriguez')")
cursor.execute("INSERT INTO bank VALUES (9891, 'Kevin Le')")

# Get Results / Querying Database
cursor.execute("SELECT username, pin FROM bank")
results = cursor.fetchall() 
print(results)
connection.commit()
# Check Database User Info  
def Log_in2():
        user_input = str(input("Enter your Username:"))
        pin_input = int(input("Enter your Pin Number:")) 
        for row in cursor.fetchall():
            if user_input and pin_input in row:
                print ("Welcome", user_input, "!")
        else: 
            print("Invalid Login Credentials")
Log_in2()



# Phase 3 (With GUI) Tkinter 

# Creating an object of class
self = Bank_Account()
# Calling functions with that class
self.options_1()
self.options_2()
self.display()

問題:

我在“# Check Database User Info”下編寫的代碼沒有檢查用戶輸入。 當輸入的密碼或用戶名不在數據庫中時,應返回“無效憑據”如何解決此問題?

為什么會發生此 UNIQUE Con​​straint 錯誤,我該如何解決?

if user_input and pin_input in row:

不是正確的方法來測試兩個輸入是否都row中。 它被解析為:

if user_input and (pin_input in row):

此外,您不能為同一個查詢調用cursor.fetchall()兩次。 cursor.fetchall()僅獲取尚未獲取的行。 一旦你調用它,所有的行都被提取了,所以沒有什么可以提取的了。 如果你想多次循環查詢結果,你應該將fetchall()的結果保存在一個列表中並使用它。

但是沒有必要遍歷所有行來判斷用戶輸入是否在表中。 首先獲取用戶輸入,並在查詢的WHERE子句中使用它。

def Log_in2():
    user_input = str(input("Enter your Username:"))
    pin_input = int(input("Enter your Pin Number:")) 
    cursor.execute("SELECT COUNT(*) FROM bank WHERE username = ? AND pin = ?", (user_input, pin_input))
    (count,) = cursor.fetchone()
    if count == 1:
        print ("Welcome", user_input, "!")
    else: 
        print("Invalid Login Credentials")

暫無
暫無

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

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