Trying to do a homework problem and nearly finished, but I keep getting this specific error.
The instructions are as such after creating the database:
After the six rows have been added, create and run SQL statements to do the following within the customerDB program:
Customer number 282 credit limit has been increased to $10,000.00, update the customer's credit limit.
Customer number 725, Deerfield's Four Seasons, is no longer a customer, delete the customer from the table.
Create a query to display all customer's names and credit limits for customer's with a credit limit of $10,000 or greater and a rep_num of 35. Order the results by credit limit in descending order.
Create a query to display all information for customers who's balance is greater than their credit limit.
import sqlite3
conn = sqlite3.connect('ABCcorpdatabase.db')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Customer')
cur.execute(""" CREATE TABLE Customer (customer_number integer,customer_name text,
balance real, credit_limit real, rep_num integer)""")
print()
print('The database and table have been creadted successfully')
Customer = [("148", "Al's Appliance and Sport", "7550.0", "7500.0","20"),
("282", "Brookings Direct", "431.5", "7500.0", "35"),
("462", "Bargains Galore", "3412.0", "10000.0", "65"),
("524", "Kline's", "12762.0", "15000.0", "35"),
("725", "Deerfield's Four Seasons", "248.75", "5000.0", "35"),
("842", "All Season", "8221.0", "7500.0", "20")]
cur.executemany ('INSERT INTO Customer VALUES (?,?,?,?,?)', Customer)
print()
print ('Data was inserted successfully')
sql = """UPDATE Customer SET credit_limit = '10000.00' WHERE customer_number = '282'"""
cur.execute(sql)
print()
print ('Update was successful')
conn.commit()
sql = """DELETE FROM Customer WHERE customer_number = '725'"""
cur.execute(sql)
print()
print('Delete was successful')
conn.commit()
print()
print('Customers with a Credit Limit >= $10,000 and Rep Num of 35: ')
sql = "SELECT credit_limit WHERE credit_limit >= 10000.0"
for row in cur.execute (sql):
print(row)
The sql statement requires a FROM clause
sql = "SELECT credit_limit FROM Customer WHERE credit_limit >= 10000.0"
In your 3rd line from the bottom you made the mistake not to specify from which table you are selecting your credit_limit. Therefore you need to add a FROM clause:
sql = "SELECT credit_limit FROM Customer WHERE credit_limit >= 10000.0"
Related
I am trying to SELECT an 'ItemID' from a table WHERE 'OrderNo' is equal to user the user's input.
I'm doing this to create a report on how ever many items the customer has purchased
However, I keep getting the same error;
cursor.execute("SELECT ItemID FROM 'Order_Line' WHERE OrderNo=?", ordernum)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.
This is what I tried;
customerID = int(input("Enter customer ID: "))
check_cid = "SELECT * FROM Customer WHERE CustomerID=?"
cursor.execute(check_cid, [customerID])
check_val = cursor.fetchone()
if check_val:
cname_query = "SELECT CustomerName FROM Customer WHERE CustomerID=?"
cursor.execute(cname_query, [customerID])
cname = cursor.fetchone()
connection.commit()
# All items customer has ordered and total quantity of each item ordered
ordernum_query = "SELECT OrderNo FROM 'Order' WHERE CustomerID=?"
cursor.execute(ordernum_query, [customerID])
ordernum = cursor.fetchall()
connection.commit()
cursor.execute("SELECT ItemID FROM 'Order_Line' WHERE OrderNo=?", ordernum)
itemid = cursor.fetchone()
connection.commit()
print(itemid)
itemname_query = "SELECT ItemName FROM Inventory WHERE ItemID=?"
cursor.execute(itemname_query, [itemid])
itemname = cursor.fetchone()
connection.commit()
print(itemname)
I was hoping to create a list of all items they have ordered and the total quantity of each item ordered - but I'm totally clueless on how to achieve this (I was thinking of a dictionary but I'm not sure), any help would be appreciated on how to do this.
The problem is that ordernum is a list of tuples containing all of the customer's order numbers. If you just want one order, you can index it.
Also, itemid is a tuple, you shouldn't put it into a list in the next query. Even when you query a single column, fetchone() will put it into a tuple.
if len(ordernum) > 0:
cursor.execute("SELECT ItemID FROM 'Order_Line' WHERE OrderNo=?", ordernum[0])
itemid = cursor.fetchone()
print(itemid)
itemname_query = "SELECT ItemName FROM Inventory WHERE ItemID=?"
cursor.execute(itemname_query, itemid)
itemname = cursor.fetchone()
connection.commit()
print(itemname)else:
print("No orders for this customer")
But you can do this all in one query that joins all the tables:
SELECT c.CustomerName, o.OrderNo, ol.ItemID, i.ItemName
FROM customer AS c
JOIN Order AS o ON o.CustomerID = c.CustomerID
JOIN Order_Line AS ol ON ol.OrderNo = o.OrderNo
JOIN Inventory AS i ON i.ItemID = ol.ItemID
WHERE c.CustomerID = ?
LIMIT 1
I'm trying to solve this exercise, and I have no clue why my SQLite DB won't update. Here is what I tried. Any ideas would be much appreciated:
Also, I forgot how to keep the program running, I mean to keep showing the user the options he has :(
import sqlite3
conn = sqlite3.connect("Books")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS Books(
id INT PRIMARY KEY,
title TEXT,
year INT);
""")
user_input = input ("Dear User, you have the following two options, two and only two (case sensitive): \n\t 1. INSERT \n\t 2. SHOW BOOKS \nPlease insert your comamnd here: <<< ")
if user_input == "1. INSERT":
book_id = input("Book id: ")
book_title = input("Book title: ")
book_year = input ("Book year of publication: ")
cursor.execute
(""" INSERT INTO Books (id, title, year) VALUES (?,?,?)
""", (book_id, book_title, book_year))
conn.commit()
print("Book inserted succesfully!")
elif user_input == "2. SHOW BOOKS":
cursor.execute("SELECT * FROM Books;")
all_results = cursor.fetchall()
print(all_results)
else:
print("Not a valid command. Try again! It's all case sensitive in Python, u know...")
if (conn):
conn.close()
I need to extract results from a redshift database based on an IF condition written in Python.
Suppose I have a table with CustomerID, SHipment Number, Invoice Station, ect as columns in Redshift table, I want to get all the records from Redshift table if customer ID exists which should be checked with user input.
TABLE NAME = ShipmentInfo
COLUMNS = CustomerID, BillNumber, Invoicing Station, Charges, etc.
Python
import psycopg2
con=psycopg2.connect(dbname= 'datamodel', host='123',
port= '5439', user= 'bce', password= 'Ciz')
cur = con.cursor()
HWB = input("Enter the House Bill Number : ")
#if CustomerID = HWB:
cur.execute("SELECT source_system, file_nbr, file_date, CustomerID
FROM public.shipment_info where CustomerID = $HWB")
results = cur.fetchall()
cur.close()
con.close()
print(results)
Consider parameterization of user input value (else risk the infamous, Bobby Tables).
# PREPARED STATEMENT WITH PLACEHOLDER
sql = """SELECT source_system, file_nbr, file_date, CustomerID
FROM public.shipment_info
WHERE CustomerID = %s
"""
# BIND PARAM VALUES WITH TUPLE OF ONE-ITEM
cur.execute(sql, (HWB,))
This is my code:
db = MySQLdb.connect("localhost", "root", "raspberry", "cribdb")
curs=db.cursor()
curs.execute ("""INSERT INTO tbstatus values(NOT NULL, 'status')""")
db.commit()
number_of_rows= curs.execute("SELECT * FROM tbstatus")
if (number_of_rows <= 5):
print(number_of_rows)
else:
curs.execute("""SELECT * from tbstatus""")
row1=curs.fetchone()
db.commit()
curs.execute("""Delete from tbstatus where id = 'row1'""")
db.commit()
print("\n Record Deleted successfully ")
It has no error but the delete function is not working. I just want to delete the first row of my database after it reach its maximum limit which is 5. What should I do? THANK YOU!
Try to use limit instead of ID
curs.execute("""DELETE FROM tbstatus order by id LIMIT 1""")
First you need to define the order of the records with order by. Then you can delete just one record with limit 1
Delete from tbstatus
order by id
limit 1
def makeProductTable():
"""This creates a database with a blank table."""
with connect("products.db") as db:
cursor = db.cursor()
cursor.execute("""
CREATE TABLE Product(
ProductID integer,
GTIN integer,
Description string,
StockLevel integer,
Primary Key(ProductID));""")
db.commit()
def editStockLevel():
with connect("products.db") as db:
cursor = db.cursor()
Product_ID=input("Please enter the id of the product you would like to change: ")
Stock_Update=input("Please enter the new stock level: ")
sql = "update product set StockLevel = ('Stock_Update') where ProductID = ('Product_ID');"
cursor.execute(sql)
db.commit()
return "Stock Level Updated."
The first function is used to make the table and it shows my column titles, the second function is needed to update a specific value in the table.
But when this is ran the inputs are executed, however when all show all the products in the table the value for stock level doesn't change.
So I think the problem has something to do with the cursor.execute(sql) line.
Or something like this?
cur.execute("UPDATE Product set StockLevel = ? where ProductID = ?",(Stock_Update,Product_ID))
Yes; you're passing literal strings, instead of the values returned from your input calls. You need to use parameters in the statement and pass thme to the execute call.
sql= "update product set StockLevel = %s where ProductID = %s;"
cursor.execute(sql, (Stock_Update, Product_ID))