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()
Related
The code works when I run it but when I run it again the data from the previous run is not saved, but the table is still there. I have tried many methods of saving the file and it still doesn't save
import sqlite3
conn = sqlite3.connect('conntact.db')
cursor = conn.cursor()
check = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='contacts'");
if check == 0:
cursor.execute('''CREATE TABLE contacts
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
EMAIL TEXT NOT NULL,
PHONE TEXT NOT NULL);''');
def add_contacts():
name1 = input("Enter contact name: ")
email1 = input("Enter contact email: ")
phone1 = input("Enter contact phone number: ")
id_s = input("Enter id: ")
cursor.execute("INSERT INTO contacts (ID, NAME,EMAIL,PHONE) VALUES (?,?,?,?)", (id_s, name1, email1, phone1));
def read_all_contact():
cursor.execute("SELECT * FROM contacts");
records = cursor.fetchall()
print(f"Total rows are: {len(records)}")
for row in records:
print(f'ID: {row[0]}')
print(f'Name: {row[1]}')
print(f'Email: {row[2]}')
print(f'Phone: {row[3]}\n')
add_contacts()
read_all_contact()
conn.close()
Any help would a apreciated
Remove check = ... line, which is wrong anyway.
Remove if check == 0
Replace "CREATE TABLE contacts" with "CREATE TABLE IF NOT EXISTS contacts"
Execute conn.commit()
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.
This code gets the category from users input in film_list table and gets IDs of all the movies with that category:
kategorija=input("Enter the category: ")
c.execute("SELECT DISTINCT FID FROM film_list WHERE category=?", (kategorija,))
filmid = c.fetchall()
print(filmid)
I'm trying to get a name and the release year of the film with the ID that we got in a previous code fragment.
result = []
for a in filmid:
c.execute("SELECT title,release_year FROM film WHERE film_id = 'a'")
result.append(c.fetchone())
print(result)
When I enter any number, for example 1, it returns what I need, so I suppose there's something wrong in the declaration of film_id, but I don't know how I can solve this.
Full code:
import sqlite3
#Connectin to DB
conn = sqlite3.connect('sakila.db')
c = conn.cursor()
#Checking if the connection to the DB is successful
if (conn):
print("Connection successful")
else:
print ("Connection unsuccessful")
kategorija=input("Enter the category: ")
c.execute("SELECT DISTINCT FID FROM film_list WHERE category=?", (kategorija,))
filmid = c.fetchall()
print(filmid)
result = []
for a in filmid:
c.execute("SELECT title,release_year FROM film WHERE film_id = 'a'")
result.append(c.fetchone())
print(result)
You may use the following single query:
SELECT f.title, f.release_year
FROM film f
INNER JOIN film_list fl ON fl.fid = f.film_id
WHERE fl.category = ?
Your updated Python code:
sql = '''SELECT f.title, f.release_year
FROM film f
INNER JOIN film_list fl ON fl.fid = f.film_id
WHERE fl.category = ?'''
kategorija = input("Enter the category: ")
result = []
c.execute(sql, (kategorija,))
result.append(c.fetchAll())
print(result)
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]))
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))