updating a database using SQLite - python

i am trying to edit a record from my database by letting the user select what they want to edit within that record.
i get the following error
UnboundLocalError: local variable 'Type' referenced before assignment
my code is as following:
import sqlite3
def update_data(values):
with sqlite3.connect("mrsimms.db")as db:
cursor = db.cursor()
sql = "Update Stock set Type=?,RetailPrice=?, NumberInStock=? where Name=?"
cursor.execute(sql,values)
db.commit()
def update():
Update = "y"
while Update == "y":
Name = input("Please enter the name of the product you wish to update: ")
Type_change=input('would you like to edit the type?(y/n) ')
if Type_change == 'y':
Type=input("Please enter the updated type: ")
RetailPrice_change=input('would you like to edit the retail price?(y/n) ')
if RetailPrice_change=='y':
RetailPrice = input("Please enter the updated retail price: ")
NumberInStock_change=input('would you like to edit the number in stock?(y/n) ')
if NumberInStock_change=='y':
NumberInStock = input("Please enter the updated number in stock: ")
data = (Type,RetailPrice,NumberInStock)
update_data(data)
Update = input("Do you wish to update another lesson? (y/n) ")
print()
update()
thank you :)

You have this code.
if Type_change == 'y':
Type=input("Please enter the updated type: ")
There is no else and Type is not assigned to later.
So here
data = (Type,RetailPrice,NumberInStock)
Type dos not exist if the ifcondition was not true.
Add an else clause or initialize Type outside the if.

Related

How can I get a single column in python and sql?

I am trying to make a book selling system and I am trying to take the book's name from input and find the quantity of the book.But system takes the whole row instead of taking a single column.How can I solve this ?
import sqlite3
print("------------------------------------------")
print("Welcome to the bookshop management system.")
print("------------------------------------------")
print("[1] Add Book")
print("[2] Search for a book")
print("[3] Sell a book")
print("[4] Change stocks")
connect=sqlite3.connect("librarydatabase.db")
cursor=connect.cursor()
Inserter="INSERT INTO books VALUES('booknamevalue','writervalue','DateOfReleasevalue','Quantityvalue','Pagevalue')"
operation=input("Please enter an operation:")
if operation=="1":
bookname=input("Please enter the book's name")
writername=input("Please enter the writer's name:")
DateOfReleaseinput=input("Please enter the Date of release:")
Quantityvalue=input("Please enter the Quantity of the book:")
Pagevalue=input("Please enter the Page count of the book:")
Inserter1=Inserter.replace("booknamevalue",bookname)
Inserter2=Inserter1.replace("writervalue",writername)
Inserter3=Inserter2.replace("DateOfReleasevalue",DateOfReleaseinput)
Inserter4=Inserter3.replace("Quantityvalue",Quantityvalue)
Inserter5=Inserter4.replace("Pagevalue",Pagevalue)
cursor.execute(Inserter5)
connect.commit()
Booksellersearcher="SELECT Quantity FROM Books WHERE Bookname='Booknamevalue'"
#Will be made correctly
if operation=="3":
Bookname2=input("Please enter the name of the book:")
Booksellersearcher2=Booksellersearcher.replace("Booknamevalue",Bookname2)
cursor.execute(Booksellersearcher2)
BookQuantity=cursor.fetchone()
if BookQuantity==0:
print("No Stock On this Book")
operation=input("Please enter an operation:")
else:
print("There are"+" "+str(BookQuantity)+"books"+" "+"of"+" "+Bookname2)
operationinput=input("Do you wanna sell ?(Y/N)")
if operationinput=="Y":
SellingQuantityInput=int(input("How many Books do you wanna sell ?"))
NewQuantity=BookQuantity-SellingQuantityInput
print(NewQuantity)
else:
operation=input("Please enter an operation:")
Booksearcher="SELECT * FROM Books WHERE Bookname='Booknamevalue'"
if operation=="2":
Booknameinput2=input("Please enter the name of the book:")
Booksearcher2=Booksearcher.replace("Booknamevalue",Booknameinput2)
cursor.execute(Booksearcher2)
Bookvalues=cursor.fetchall()
print(Bookvalues)
BookQuantitychanger="UPDATE Books SET Quantity='Quantityvalue' WHERE Bookname='Booknamevalue'"
if operation=="4":
Booknameinput3=input("Please enter the name of the book:")
BookQuantityinput=int(input("Please enter the quantity of the book:"))
BookQuantitychanger2=BookQuantitychanger.replace("Quantityvalue",str(BookQuantityinput))
BookNamereplacer=BookQuantitychanger2.replace("Booknamevalue",Booknameinput3)
cursor.execute(BookNamereplacer)
connect.commit()
print("Book quantity changed successfully!")
I will start with your question, SELECT on a table will return rows, which are put in tuples, even you select a single columns it returns the rows containing just this column, but those are still rows, and so tuples.
But now please read the following.
Using string replace or any other other string templating for any SQL statement is leaving it wide open for SQL injection, what if the user inputs ' ; DROP TABLE books ; -- in the Booksearcher statement ?
You end up with
SELECT * FROM Books WHERE Bookname='' ; DROP TABLE books ; --'
which will destroy you books table.
Please go through the SQLite3 tutorial to see SQL parameterisation.
Your SQL statement is SELECT * which is why you get all columns.
Change your SQL statement to the one below:
Booksearcher="SELECT Quantity FROM Books WHERE Bookname='Booknamevalue'"
But your code is a bit unreadable.
You are using a lot of replacements and for each you're using a new variable. Use f-strings instead.
Your variable names are capitalized. In python that's used to define classes/objects.
Your if statements should be if/elif instead.
There is no main loop, so your code only executes once.
You have what I would call main menu prints inside your submenus. Instead you should go back to the main menu.
Little Bobby Tables
I did a quick rewrite of your code because I'm a bit bored. See below
import sqlite3
connect = sqlite3.connect("librarydatabase.db")
cursor = connect.cursor()
while True:
print("------------------------------------------")
print("Welcome to the bookshop management system.")
print("------------------------------------------")
print("[1] Add Book")
print("[2] Search for a book")
print("[3] Sell a book")
print("[4] Change stocks")
print("[0] Exit")
operation = input("Please enter an operation:\n")
if operation == "1":
bookname = input("Please enter the book's name:\n")
writername = input("Please enter the writer's name:\n")
dateofrelease = input("Please enter the Date of release:\n")
quantity = input("Please enter the Quantity of the book:\n")
pagecount = input("Please enter the Page count of the book:\n")
cursor.execute(f"INSERT INTO books VALUES('{bookname}','{writername}','{dateofrelease}','{quantity}','{pagecount}')")
connect.commit()
elif operation == "2":
bookname = input("Please enter the name of the book:\n")
cursor.execute(f"SELECT Quantity FROM Books WHERE Bookname='{bookname}'")
books = cursor.fetchall()
print(books)
elif operation == "3":
bookname = input("Please enter the name of the book:\n")
cursor.execute(f"SELECT Quantity FROM Books WHERE Bookname='{bookname}'")
bookquantity = cursor.fetchone()
if bookquantity == 0:
print("No Stock On this Book")
# go to the start of the while loop
continue
else:
print(f"There are {bookquantity} books of {bookname}")
operationinput = input("Do you wanna sell ?(Y/N):\n")
if operationinput.upper() == "Y":
sellingquantity = int(input("How many Books do you wanna sell ?\n"))
newquantity = bookquantity - sellingquantity
print(newquantity)
else:
continue
elif operation == "4":
bookname = input("Please enter the name of the book:\n")
bookquantity = int(input("Please enter the quantity of the book:\n"))
cursor.execute(f"UPDATE Books SET Quantity='{bookquantity}' WHERE Bookname='{bookname}'")
connect.commit()
print("Book quantity changed successfully!")
elif operation == "0":
# exit while loop
break
else:
print("Operation not recognized.")

Python SQlite3 Update No Error But Does Not Updating

It shows no error and is able to run, but the data in the SQLite table doesn't update. However other update function similar to this work
def seller_edit():
while True:
sellername = str(input("Enter your username: "))
with sqlite3.connect(r"C:\Users\User\Desktop\HFSystem\Assginment\HFuserinfo.db") as connect:
cursor = connect.cursor()
check = "SELECT * FROM sellerinfo WHERE Username = ?"
cursor.execute(check,[sellername])
results = cursor.fetchall()
if results:
Phone = int(input("Enter New Phone No.: "))
Email = str(input("Enter New Email: "))
Address = str(input("Enter New Address: "))
updateseller ="""UPDATE sellerinfo SET Phone = ?, Email=?,Address=? WHERE Username=?"""
cursor.execute(updateseller,[sellername,Phone,Email,Address])
connect.commit()
print("Seller Info Edited!")
connect.close()
seller_info_menu()
break
else:
print("ProductID does not recognised")
option = input("Do you want to try again (y/n): ")
if option.lower() == "n":
seller_info_menu()
break
The order of the parameters inside the tuple of the 2nd argument of cursor.execute() must be the same as the order of the ? paceholders:
cursor.execute(updateseller, (Phone, Email, Address, sellername))

How do I keep two arrays parallel arrays?

The user needs to input the table number (Tables are numbered from 0 to 19). If the table is not available (reserved), inform the user that the selected table is not available. If the table is available, then ask for the name (name is a single word, no space) and mark the table as reserved. Now I need to keep two arrays (parallel arrays!), both are size 20, one of type boolean (true/false -- reserved/available) and the other one of type string (name on reservation if reserved, blank otherwise)
tableNum = []
def reserve():
global table
global name
global tableNum
avaible = False
tablenum = int(input("Enter a number: "))
if not tablenum in tableNum:
name = input("Table is avaiable, please enter your name: ")
else:
print("Table is unavaiable")
while(True):
print("1- Reserve a Table")
print("2- Clear Reservation")
print("3- Report")
print("0- Exit")
choice = int(input("Choose a option "))
if choice == 1:
reserve()
You could do it without keeping a list of all the tables. Append reservations as a key, value pair to a dictionary. You can then check if the input matches a key in the reservation dictionary. You can then use the reverse to remove a reservation.
reservationDictionary ={}
def reserve():
global reservationDictionary
tablechoice = int(input('Tables are numbered 0-19, Choose a table number'))
if tablechoice not in reservationDictionary.keys():
name = input("Table is available, enter your Name: ")
reservationDictionary[tablechoice] = name
else:
print("Table is unavailable")
Update to remove a booking:
def removeReservation():
global reservationDictionary
removetable = int(input('Choose table number to remove reservation for that table'))
if removetable not in reservationDictionary.keys():
print("This table doesn't have a reservation")
else:
del reservationDictionary[removetable]
print("Reservations for table {} has been deleted".format(removetable))

Greeting name taken from the dictionary

pins = {"Mike":1234, "Joe":1111, "Jack":2222}
pin = int(input("Enter your pin: "))
if pin in pins.values():
nameinp = pins.get(pin)
print("Hello Mr." + nameinp)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for key in pins.keys():
print(key)
input()
So the idea is to make greeting screen for the particular person who inserted his own pin code, tried to research didn't find the answer, hope you will help!
Answers to all of you
There is no error, there is a question:
how to make that when you put in password that is equal some value, and later when the system recognizes your password prints("Greetings" + value)
You have the order of the dictionary key-value pairs interchanged. So instead of
pins = {"Mike":1234, "Joe":1111, "Jack":2222}
you should do
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
I took the liberty to change the variable name to be more descriptive what it actually does: Given a pin it returns the username. For example: user_from_pin[1111] == "Joe". The rest of the script should be adapted a little bit to work with this definition:
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
pin = int(input("Enter your pin: "))
user = user_from_pin.get(pin)
if user:
print("Hello Mr." + user)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for value in pins.values():
print(values)
input()

How to insert data into specific row without hardcode

The aim of this code is to achieve the following:
-Enter username
-Check if exists on DB
-If not create new user
-Add currency & balance to new user row
The issue is with my insert statement. I'm not sure how to use the WHERE condition while inserting data using defined variables. Help would be welcomed!
Error Message: TypeError: function takes at most 2 arguments (4 given)
def add_user():strong text
print("enter new username")
UserLogin = str(input())
c.execute("SELECT username FROM FinanceDBTable")
enter code here
for row in c.fetchall():
print()
#Convers tuple to string without spaces
UserNameDB = ''.join(row)
if UserNameDB == UserLogin:
print('This username already exisits. please try again')
add_user()
else:
print("Please enter your balanace\n")
userbalance = input()
print("Please enter currency\n")
userCurrency = input()
c.execute("INSERT INTO FinanceDBTable (balance, currency) VALUES (?,?)",
(userbalance, userCurrency), "WHERE (username) VALUES (?)", (UserLogin))
conn.commit()
One way would be to do this, also does not use recursion which is seen as unpythonic and also will eventually throw errors. Plus made it a bit more pythonic.
I'm not sure if you can use WHERE in INSERT statements, you can in UPDATE maybe that where you're getting that idea from, but by also giving the username value with the other will work for what you are trying to achieve i think.
def add_user():
while True:
username = input("Username: ")
c.execute("SELECT username FROM FinanceDBTable WHERE username = ?", (username,))
results = c.fetchall()
if len(results) < 1:
# Add user as there is not user with that username.
user_balance = int(input("Please enter your balance: "))
user_currency = input("Please enter currency: ")
c.execute("INSERT INTO FinanceDBTable(username, balance, currency) VALUES (?,?,?)", (username, user_balance, user_currency))
conn.commit()
break
else:
# User already exists
print('This username already exists, please try again.')

Categories

Resources