How can I merge old data with new data - python

Hi I currently want to show the product cart to the customer which means i need to get the data from the old table which are the products and the new table which is the quanity of the product that they want but when the data is inserted it acts as 2 different things so it does not merge, this is the code that i have thus far;
def add_to_productcart():
while True:
buyername = str(input("Please Enter Your Username: "))
print("="*25)
print(f"{buyername}'s Product Cart")
print("="*25)
ProductID = str(input("Please Enter ProductID that you want to buy: "))
with sqlite3.connect(r"C:\Users\User\Desktop\HFSystem\Assginment\HFuserinfo.db") as connect:
cursor = connect.cursor()
idcheck = """SELECT *FROM products WHERE ProductID = ?"""
idchecked = cursor.execute(idcheck,[ProductID])
if (idchecked):
Quantity = int(input("Enter the Quantity You Want: "))
Totalprice = 0
first=("""INSERT INTO productcarts(Buyername,Quantity,Totalprice)VALUES(?,?,?)""")
cursor.execute(first,[buyername,Quantity,Totalprice])
products = """INSERT INTO productcarts
(ProductID,
ProductName,
ProductPrice,
Produced,
ExpiryDate)
SELECT ProductID,
ProductName,
ProductPrice,
Produced,
ExpiryDate
FROM products WHERE ProductID = ?
"""
added = cursor.execute(products,[ProductID])
connect.commit()
if (added):
print(f"Product{ProductID} added into {buyername}'s cart")
productcart_menu()
else:
print(f"Product{ProductID} failed to add into {buyername}'s cart")
productcart_menu()
connect.close()
else:
print(f"Product{ProductID} not found! Please Try Again!")
return productcart_menu()
I realised the error is that i have 2 executes so that the data inserted does not act as a whole but when i changed it i keep getting errors, any suggestions are welcomed thank you.

Related

What is wrong with this code that it is not able to increment the stock by one in my Database

I have written this code in python and using SQLite to interact with my database. I want the user to be able to return an item which is purchased, which works functionally, but now I need to actually increment the stock by 1 when an item is returned.
The code so far is like this:
itemToReturn = input("Enter the OrderItemsID of the item you want to return: ")
# sql statement to locate record based on input
itemToReturnSQL = '''UPDATE OrderItems
SET OrderItemStatus = 'Returned'
WHERE OrderItemsID = ?
'''
locateItemSQL = c.execute("SELECT ProductID FROM OrderItems WHERE OrderItemsID= ?", (
itemToReturn,))
locateItem = c.fetchall()
returnStockSQL = '''UPDATE Products
SET ProductStock = ProductStock + 1
WHERE ProductID = ?'''
# executes the sql
conn.execute(itemToReturnSQL, (itemToReturn,))
conn.execute(returnStockSQL, (locateItem[0][0],))
# saves
conn.commit()
Orders are divided into 2 tables:
Order: OrderID (Auto increment) UserID (foreign key) Order Date
OrderItems: OrderItemsID (Auto) OrderID (foreign key) ProductID(Foreign Key)
No errors are given now, but the stock still does not increment.

How do I create an SQLite record for each item in a list

I've written this code to create a list of user inputs which represent products in an SQLite DB table.
The list is referred to as basket, and now for each item in basket I want to create a record in another table which contains the orderID from the record I just created and the product ID which will come from the basket.
My current solution is very messy and looks like this:
shopping = True
while shopping:
itemToAdd = input("Please enter the ID of the item to add to the basket: ")
basket.append(itemToAdd)
print(basket)
continueShop = input("Continue shopping?(y/n): ")
if continueShop == "n":
conn.execute("INSERT INTO Orders (UserID) VALUES (?)", (results[0][0],))
conn.commit()
counter = 0
for items in basket:
createOrderItems = "INSERT INTO OrderItems (OrderID, ProductID) VALUES (?,?)"
currentOrder = "SELECT * FROM Orders WHERE UserID = (?)"
conn.execute(currentOrder, (results[0][0],))
conn.execute(createOrderItems, (currentOrder, basket(counter)))
counter = +1
Currently this gives the error
line 108, in <module>
conn.execute(createOrderItems, (currentOrder, basket(counter)))
TypeError: 'list' object is not callable
googling the problem was giving me the exact opposite of what I was trying to find so sorry if this is a poor question, I'm just really lost with this now having tried all I could think of.
UPDATE:
shopping = True
while shopping:
itemToAdd = input("Please enter the ID of the item to add to the basket: ")
basket.append(itemToAdd)
print(basket)
continueShop = input("Continue shopping?(y/n): ")
if continueShop == "n":
conn.execute("INSERT INTO Orders (UserID) VALUES (?)", (results[0][0],))
conn.commit()
counter = 0
for items in basket:
createOrderItems = "INSERT INTO OrderItems (OrderID, ProductID) VALUES (?,?)"
currentOrder = ("SELECT * FROM Orders WHERE UserID = (?)", (results[0][0]))
conn.execute(createOrderItems, (currentOrder, basket[counter]))
counter = +1
conn.commit()
Updated the code to include basket[counter] instead of basket(counter) and that got rid of the error, however the raw sql statement itself was being added to the table instead of the ID the statement is meant to locate so I have attempted to fix that aswell by changing currentOrder, however it now gives this error:
line 107, in <module>
conn.execute(createOrderItems, (currentOrder, basket[counter]))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
Change this:
basket(counter)
To this:
basket[counter]
Also, currentOrder in same line must be an id, you currently pass the entire sql statement. Try to pass the
currentOrder[0][x]
where x is the column position (1st, 2nd, 5fth, etc) of the column that represents the OrderId in your Orders table. So, this line should become:
conn.execute(createOrderItems, (currentOrder[0][x], basket[counter]))

Enter data into a SQL table in python?

I'm making a program that connects to a SQL database for me to enter in data. Instead of entering data into the table manually, I wanted to make a program do it. So it's asks me a series of questions, then inputs the answers into the table. I am not sure how to do that. My issue is at the end with the cursor execute.
I am not sure how I can incorporate the input answers into that execute function. Would it be something like this? The .format is showing up as a string, so I am not sure how to implement this.
VALUES
('{}'.format(category), '{}'.format(description), '{}'.format(date), '{}'.format(price), '{}'.format(vehicle))
Here is the code below:
import time
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TJDESKTOPPC;'
'Database=carparts;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM carparts.dbo.modifications
''')
conn.commit()
# Menu starts below
database = "carparts"
print("Welcome to the program!")
print()
print("You are connected to {} database".format(database))
print()
print()
print("The current columns in the table are...")
print()
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TJDESKTOPPC;'
'Database=carparts;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM carparts.dbo.modifications where 1=2')
headers = [i[0] for i in cursor.description]
print(headers)
print()
print("Categories are: engine, suspension, exhaust, or transmission")
print()
category = str(input("Please enter category: "))
print()
description = str(input("Please enter the description of the part: "))
print()
purchase_date = input("Please enter the purchase date in (YYYY-MM-DD): ")
print()
price = int(input("Please enter the price amount: "))
print()
vehicle = str(input("What vehicle is this for? (Model): "))
print()
print("Thanks!")
time.sleep(3)
print("\n" * 5) # This will the clear screen of any previous code
print("Adding the category, description, purchase date, price, and vehicle to the table...")
time.sleep(2)
cursor.execute('''
INSERT INTO carparts.dbo.modifications (category, description, purchase_date, price,
vehicle)
VALUES
('exhaust', 'Flowmaster Cat-back Exhaust', '2015-12-08', '551', 'focus_st')
''')
conn.commit()
The snippet above for INSERT INTO actually works, but I need to put the values in manually how it is. So how do I get the variable input (category, description, date, etc) in that string?
Try this,
Here you need to provide your variable data you want to insert and also need to add {} in single quotes like this '{}'.
So that your after providing value in format "'{}'".format("category_input") is looks like 'category_input' and it doesn't effect if you have a number.
cursor.execute('''INSERT INTO carparts.dbo.modifications (category, description,
purchase_date, price, vehicle) VALUES ('{}', '{}', '{}', '{}', '{}')'''.format(category, description, purchase_date, price, vehicle))

Python Sqlite None Type Error - works if query executed outside function

I am trying to add the below function to my script.
I want a user to be able to search a database. Be presented with all possible choices and then be able to search based on a unique book_id to avoid duplicates.
The entire function is below:
# 2 - function to update a book
def update_book():
'''Takes in new information about a book and replaces the the information in the database
Allows user to search via title or author
Then displays all matches and requests the unique book_id in the event that the search returns more
than one result for an author or title. This ensures correct book is updated
Search by title and author rather than book_id as it is very unlikely a store clerk could remember every unique book_id
when the database becomes larger
parameters - None
Returns - None.
Prints what has been amended in the db, displaying previous info and new updated info.'''
print("You want to update a book, do you want to search by the author or the book title?")
search_item = input(" To search by author - Enter a\n To search by title - Enter t")
if search_item.strip().lower() == "a":
# ask user if they know the full author name or only a portion
# if only a portion implement wildcards in the search and direct user to then search off of book_id
print("\nDo you know the authors initials and surname or do you only know part of the name?")
partial_or_full = input(" If you know the full details of the author enter full, otherwise press enter and a search on a partial name will be done")
if partial_or_full.strip().lower() == "full":
# added check to ensure database contains search results
while True:
author_search = input("Please enter the authors full name")
print ("\nThe database contains the below results for the author")
# display all matches for the author
cursor.execute('''SELECT * from books WHERE author=?''', (author_search,))
if cursor is None:
print("The database has no results for that author")
print("Double check your spelling and try again")
continue
else:
for row in cursor:
print(f"book_id: {row[0]}, Title: {row[1]}, Author: {row[2]}, Stock: {row[3]}")
print("\nPlease select your book from the above")
book_to_change = int(input("Enter the book's unique book_id ").strip())
else:
# make use of wildcards in search
# in the event that the store clerk did not have the full author name
# added check for if the user results returns nothing in the event of a partial entry
while True:
author_search = input("\nPlease enter the known piece of the author's name to search ")
wild_card_search = "%"+author_search+"%"
cursor.execute('''SELECT * FROM books WHERE author LIKE ?''', (wild_card_search,))
if cursor is None:
print("\nThe Database contains no similar search results")
print("Double check your spelling and try again")
continue
else:
print("Search results will be printed below:")
for row in cursor:
print(f"book_id: {row[0]}, Title: {row[1]}, Author: {row[2]}, Stock: {row[3]}")
break
print("\nPlease select your book from the above")
book_to_change = int(input("Enter the book's unique book_id ").strip())
# based on book_id retrieve the previous database info
cursor.execute('''SELECT * FROM books WHERE book_id=?''', (book_to_change,))
old_title = cursor.fetchone()[1]
old_author = cursor.fetchone()[2]
old_stock = cursor.fetchone()[3]
# request updated information from the user
print("\nPlease enter the new information for the book")
print("If you want to leave a value unchanged please enter the previous value")
book_title = input("\nPlease enter the previous or ammended Title of the book ")
book_author = input("\nPlease enter the previous or ammended Author of the book ")
book_stock = int(input("\nPlease enter the previous or ammended Stock on hand "))
# add changes to the database
cursor.execute(''' UPDATE books SET (Title = ?,Author = ?,Qty = ?) WHERE book_id = ? ''', (book_title,book_author,book_stock,book_id))
db.commit()
print(f"\n Thank you, the below changes have been made to book_id: {book_id}")
print("The information has been changed FROM:")
print(f'''Title: {old_title}
Author: {old_author}
Stock on Hand: {old_stock}''')
print("To the following:")
print(f'''Title: {book_title}
Author: {book_author}
Stock: {book_stock}''')
print("\n Data base updated and ready for query....")
elif search_item.strip().lower() == "t":
# ask user if they know the full title or only a portion
# if only a portion implement wildcards in the search and direct user to then search off of book_id
print("\nDo you know the full title or only the beginning?")
partial_or_full = input("If you know the full title enter full otherwise press enter and a search on a partial title will be done")
if partial_or_full.strip().lower() == "full":
# added check to ensure database contains search results
while True:
title_search = input("Please enter the full title")
print ("\nThe database contains the below results for the author")
# display all matches for the author
cursor.execute('''SELECT * from books WHERE title=?''', (title_search,))
if cursor is None:
print("The database has no results for that title")
print("Double check your spelling and try again")
continue
else:
for row in cursor:
print(f"book_id: {row[0]}, Title: {row[1]}, Author: {row[2]}, Stock: {row[3]}")
break
print("\nPlease select your book from the above")
book_to_change = int(input("Enter the book's unique book_id ").strip())
else:
# make use of wildcards in search
# in the event that the store clerk did not have the full title
# added check for if the user results returns nothing in the event of a partial entry
while True:
title_search = input("\nPlease enter the portion of the title that is known ")
wild_card_search = "%"+title_search+"%"
cursor.execute('''SELECT * FROM books WHERE title LIKE ?''', (wild_card_search,))
print("Search results will be printed below:")
if cursor is None:
print("\nThe Database contains no similar search results")
print("Double check your spelling and try again")
continue
else:
print("Search results will be printed below:")
for row in cursor:
print(f"book_id: {row[0]}, Title: {row[1]}, Author: {row[2]}, Stock: {row[3]}")
break
print("\nPlease select your book from the above")
book_to_change = int(input("Enter the books unique book_id ").strip())
# based on book_id retrieve the previous database info
cursor.execute('''SELECT * FROM books WHERE book_id=?''', (book_to_change,))
old_title = cursor.fetchone()[1]
old_author = cursor.fetchone()[2]
old_stock = cursor.fetchone()[3]
# request updated information from the user
print("\nPlease enter the new information for the book")
print("If you want to leave a value unchanged please enter the previous value")
book_title = input("\nPlease enter the previous or ammended Title of the book ")
book_author = input("\nPlease enter the previous or ammended Author of the book ")
book_stock = int(input("\nPlease enter the previous or ammended Stock on hand "))
# add changes to the database
cursor.execute(''' UPDATE books SET (Title = ?,Author = ?,Qty = ?) WHERE book_id = ? ''', (book_title,book_author,book_stock,book_id))
db.commit()
print(f"\n Thank you, the below changes have been made to book_id: {book_id}")
print("The information has been changed FROM:")
print(f'''Title: {old_title}
Author: {old_author}
Stock on Hand: {old_stock}''')
print("To the following:")
print(f'''Title: {book_title}
Author: {book_author}
Stock: {book_stock}''')
print("\n Data base updated and ready for query....")
The piece that is giving me issues is when asking for the book_id
Like so
print("\nPlease select your book from the above")
book_to_change = int(input("Enter the book's unique book_id ").strip())
# based on book_id retrieve the previous database info
cursor.execute('''SELECT * FROM books WHERE book_id=?''', (book_to_change,))
old_title = cursor.fetchone()[1]
old_author = cursor.fetchone()[2]
old_stock = cursor.fetchone()[3]
I am able to take the user input and store it as book_to_change.
However I get the below error when trying to store the old author, title and stock.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-2c02560967f4> in <module>
----> 1 update_book()
<ipython-input-19-8bc56328ea70> in update_book()
79
80 old_title = cursor.fetchone()[1]
---> 81 old_author = cursor.fetchone()[2]
82 old_stock = cursor.fetchone()[3]
83
TypeError: 'NoneType' object is not subscriptable
If I execute a search outside the function I can retrieve the data and store it using this code:
book_to_change = 3002
cursor.execute('''SELECT * FROM books WHERE book_id=?''', (book_to_change,))
test = cursor.fetchone()[1]
print(test)
Output is:
Harry Potter and the Philospher's Stone
It is only when using the function that I cannot seem to get it right.
I have executed the code to make sure it works and then pasted it in exactly the same but I get the same error.
I am not sure why I cannot get it to execute when working from my function update_book
What have I done wrong?
You should use cursor.fetchone() only once
data = cursor.fetchone()
and later use
old_title = data[1]
old_author = data[2]
old_stock = data[3]
Using cursor.fetchone() second time it may try to get second row which you don't have.

Use a query in sqlite value - python

Does anyone know how to execute a query inside a value in python sqlite
The eroor i am getting is:
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
my code is here:
Name = input("Enter the name of the product you want to purchase: >>")
item = Name
qty = input("Enter the Quantity of the product you want to purchase: >>")
today = date.today()
cursor = db.cursor()
cursor.execute("SELECT CatID from Products where Name=?",(Name,))
result = cursor.fetchall()
confirm = input("are you sure you want tot buy this product (y/n): >>" )
if confirm == "y":
### In this query where it says result i want to execute the data from the result query
cursor.execute("INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) Values(?,?,?,?,?)",(Username,result,today,qty,Name))
db.commit()
print("Product purchased. Thankyou for your order")
cursor.execute("UPDATE Products SET Qty = (? -1) where Name = ?",(qty,item,))
else:
print("The program will now terminate")
You can also iterate over result:
for row in result:
cursor.execute(
"INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) SELECT CatID,?,?,?,? FROM Products WHERE Name=?",(Username,row,today,qty,Name))
db.commit()

Categories