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
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 want to SELECT and UPDATE in one query.
In my database, I have category_ids that needs to be checked. I want to select the last updated query by DESC and update it with runs = runs+1, so it counts up that and also automatically update the last_update field.
But for some reason, I can't fetch it
cursor.execute(
"UPDATE categorys as t1,
(SELECT category_id
FROM categorys
ORDER BY last_update
LIMIT 1) as t2
SET t1.runs = t1.runs+1
WHERE t2.category_id = t1.category_id")
row = cursor.fetchone()
print(row)
print(row) gives me None but I need the category_id here
The update works and counts up the runs+1 of the last_update DESC
mysql update doesn't return value of data changed. It only returns the Query ran ok.
you would need to execute the select statement to return the category_id.
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"
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))
[Using Python3.x]
The basic idea is that I have to run a first query to pull a long list of IDs (text) (about a million IDs) and use those IDs in an IN() clause in a WHERE statement in another query. I'm using python string formatting to make this happen, and works well if the number of IDs is small - say 100k - but gives me an error (pyodbc.Error: ('08S01', '[08S01] [MySQL][ODBC 5.2(a) Driver][mysqld-5.5.31-MariaDB-log]MySQL server has gone away (2006) (SQLExecDirectW)')) when the set is indeed about a million IDs long.
I tried to read into it a bit and think it might have something with the default(?) limits set by SQLite. Also I am wondering if I'm approaching this in the right way anyway.
Here's my code:
Step 1: Getting the IDs
def get_device_ids(con_str, query, tb_name):
local_con = lite.connect('temp.db')
local_cur = local_con.cursor()
local_cur.execute("DROP TABLE IF EXISTS {};".format(tb_name))
local_cur.execute("CREATE TABLE {} (id TEXT PRIMARY KEY, \
lang TEXT, first_date DATETIME);".format(tb_name))
data = create_external_con(con_str, query)
device_id_set = set()
with local_con:
for row in data:
device_id_set.update([row[0]])
local_cur.execute("INSERT INTO srv(id, lang, \
first_date) VALUES (?,?,?);", (row))
lid = local_cur.lastrowid
print("Number of rows inserted into SRV: {}".format(lid))
return device_id_set
Step 2: Generating the query with 'dynamic' IN() clause
def gen_queries(ids):
ids_list = str(', '.join("'" + id_ +"'" for id_ in ids))
query = """
SELECT e.id,
e.field2,
e.field3
FROM table e
WHERE e.id IN ({})
""".format(ids_list)
return query
Step 3: Using that query in another INSERT query
This is where things go wrong
def get_data(con_str, query, tb_name):
local_con = lite.connect('temp.db')
local_cur = local_con.cursor()
local_cur.execute("DROP TABLE IF EXISTS {};".format(tb_name))
local_cur.execute("CREATE TABLE {} (id TEXT, field1 INTEGER, \
field2 TEXT, field3 TEXT, field4 INTEGER, \
PRIMARY KEY(id, field1));".format(tb_name))
data = create_external_con(con_str, query) # <== THIS IS WHERE THAT QUERY IS INSERTED
device_id_set = set()
with local_con:
for row in data:
device_id_set.update(row[1])
local_cur.execute("INSERT INTO table2(id, field1, field2, field3, \
field4) VALUES (?,?,?,?,?);", (row))
lid = local_cur.lastrowid
print("Number of rows inserted into table2: {}".format(lid))
Any help is very much appreciated!
Edit
This is probably the right solution to my problem, however when I try to use "SET SESSION max_allowed_packet=104857600" I get the error: SESSION variable 'max_allowed_packet' is read-only. Use SET GLOBAL to assign the value (1621). Then when I try to change SESSION to GLOBAL i get an access denied message.
Insert the IDs into a (temporary) table in the same database, and then use:
... WHERE e.ID IN (SELECT ID FROM TempTable)