How to insert MAX (text) as WHERE clause? - python

I should be searching based on two WHERE clauses at the same time. One is a simple clause, the other is MAX (text). How to solve?
x = cursor.execute('SELECT product FROM electronics WHERE brand = ? AND MAX(price)' [combo_brand])
Price is a column of a database. I want to take the highest value of the column records. I would like to select the product with the maximum price, and search by it and by brand at the same time.
I am getting this error:
TypeError: string indices must be integers

If you want to select the product having the max price for a given brand, then use:
sql = '''SELECT product
FROM electronics
WHERE brand = ? AND price = (SELECT MAX(e.price)
FROM electronics e
WHERE e.brand = electronics.brand)'''
x = cursor.execute(sql, (combo_brand,))
records = cursor.fetchall()
print("Total rows are: ", len(records))
for row in records:
print(row)
If instead you want the product with the maximum price across all brands, then use:
sql = '''SELECT product
FROM electronics
WHERE brand = ? AND price = (SELECT MAX(price) FROM electronics)'''
x = cursor.execute(sql, (combo_brand,))
But I suspect the first version is what you want.

Related

Multiplying columns in SQLite3 from two different tables

I am currently working on a school project where I must develop a database application with a graphical user interface using Python, Tkinter, and SQLite3. The user enters the ProductID and quantity into a form, and I am trying to get the program to select the price of the product from the product table using the ProductID, and multiply this price by the quantity input by the user to give the total cost of the order and insert this result into the total field on the order table.
I am receiving the following error:
File "c:\Users\Ryan\OneDrive - C2k\A2 2020-2021\Computer Science\A2 Unit 5\Code\OrderForm.py", line 81, in CalculatePrice
price = ((int(quantity)*(int(x) for x in results)))
TypeError: unsupported operand type(s) for *: 'int' and 'generator'
I have carried out research into this error, however, I still cannot understand how to get this to work or if it is even possible. If anybody could take a look at my code below and try help me out with doing this, I would really appreciate it.
def CalculatePrice(self):
orderid = self.OrderIDEntry.get()
productid = self.ProductIDEntry.get()
quantity = self.QuantityEntry.get()
with sqlite3.connect("LeeOpt.db") as db:
cursor = db.cursor()
searchprice = ('''SELECT Price FROM Products WHERE ProductID = ?''')
cursor.execute(searchprice, [(productid)])
results = cursor.fetchall()
if results:
for i in results:
price = ((int(quantity)*(int(x) for x in results)))
addprice = ('''INSERT INTO Orders(OrderTotal)
VALUES (?)''')
cursor.execute(addprice, [(price)])
self.ClearEntries()
else:
tkinter.messagebox.showerror("Error", "No product was found with this ProductID, please try again.")
self.ClearEntries()
You are mixing an external loop over the results iterable, inserting 1 value at a time, and an execution of the same INSERT query over an iterable of values.
First way, external loop (I have removed some useless parentheses):
for i in results:
price = int(quantity)*int(i)
addprice = ('''INSERT INTO Orders(OrderTotal)
VALUES (?)''')
cursor.execute(addprice, [price])
Second way, using executemany:
prices = ([int(quantity)*int(x)] for x in results) # prices is an iterable of lists
addprice = ('''INSERT INTO Orders(OrderTotal)
VALUES (?)''')
cursor.executemany(addprice, prices)
But if you are learning SQL and database accesses, you could directly use joined queries:
addprice = '''INSERT INTO Orders(OrderTotal)
SELECT :quantity * Price FROM Products
WHERE Products.ProductID = :productid'''
cursor.execute(addprice, {'quantity': quantity, 'productid': productid})
And as your code contains an (unused) orderid variable, I think that what you want is:
addprice = '''INSERT INTO Orders(OrderID, OrderTotal)
SELECT :orderid, :quantity * Price FROM Products
WHERE Products.ProductID = :productid'''
cursor.execute(addprice, {'quantity': quantity, 'productid': productid,
'orderid': orderid})
Your expressions (int(x) for x in results) and (int(quantity)*(int(x) for x in results)) evaluates to a generator objects as you have enclosed it within parenthesis. See here
>>> (quant for quant in range(5))
<generator object <genexpr> at 0x1021e1780>
>>>
So remove your parenthesises and break it down into smaller chunks.
Also there should only be one price returned for a single productId, so you're looping multiple times and don't have to use tuples unless you're input itself is multiple product ids and you're multiplying each price and product and computing order total.
A simplified version might look like this
cursor.execute('SELECT Price FROM Products WHERE ProductID = ?', (productid,))
result = cursor.fetchone()
if result:
price = quantity * float(result[0])
cursor.execute('INSERT INTO Orders(OrderTotal) VALUES (?)', (price,))
self.ClearEntries()
else:
tkinter.messagebox.showerror("Error", "No product was found with this ProductID, please try again.")
self.ClearEntries()

How to iterate over columns of mysql table and return information in a spot?

I have a MySQL table and the first column of the table is company names and the second column is a keyword associated with the company. Some companies have multiple keywords and the way I did it is if a company has more than one keyword they have multiple first and second columns. output.impwords is a list containing keywords that I have gathered from processing a sentence and getting the keyword. How do I iterate through the keywords from the table and then match that with the first column of the table which is the company name?
Here is a picture of the table
My method so far
def match_tweet_for_website(self):
output= WebOutput.WebOutput(input("Enter Tweet "))
print(output.impWords)
self.cursor = self.connection.cursor(buffered=True)
query= "SELECT DISTINCT company_name FROM CompanyKeywords WHERE"
for i in output.impWords:
I think it should be something like this:
def match_tweet_for_website(self):
output= WebOutput.WebOutput(input("Enter Tweet "))
print(output.impWords)
self.cursor = self.connection.cursor(buffered=True)
query= "SELECT DISTINCT company_name FROM CompanyKeywords WHERE keyword = "
results = []
for i in output.impWords:
currentQuery = query + i
mycursor.execute(currentQuery)
result = self.cursor.fetchall()
results.append(result)
print(results)

Problem iterating through MySQL in python

I just started learning python and am trying out projects. I'm having a with my python code. What I want to do is to go through the rows in my table one after another and perform a specific task on each row.
With an example, I have rows with multiple columns and three of the columns are con_access, exam and total. Now I want to get sum of the values in con_access and exam columns and then put it in the total column. This calculation should done one by one.
The problem that am having is that the program goes to the last row, takes the total variable and populate every other with it
Below is my code
def result_total():
mdb = mysql.connector.connect(
host="localhost",
user="root",
passwd="**************",
database="majesty"
)
mycursor = mdb.cursor()
# mycursor.execute("SELECT con_access, exam FROM students")
mycursor.execute("SELECT CAST(con_access AS UNSIGNED) as con_access, CAST(exam AS UNSIGNED) as exam FROM students")
rows = mycursor.fetchall()
for row in rows:
if row:
total = row['con_access'] + row['exam']
sql = "UPDATE students SET total = {}".format(total)
mycursor.execute(sql)
mdb.commit()
find total like below
total = row['con_access'] + row['exam']
If your datatype of con_access and exam in mysql table is varchar, you should cast it. Change the select query as follows.
SELECT CAST(con_access AS UNSIGNED) as con_access, CAST(exam AS UNSIGNED) as exam FROM students

how to find the sum of multiple numbers from a column in a sql database in python?

I have a database that has a bookings table in. One of the columns in the bookings table is 'incomes', and another one is 'date_of_booking,' which stores dates in 'DD/MM/YYYY' format. I am trying to write a feature that lets a user input a month, and from that will calculate all the incomes from that month. So far I have this:
validMonth = False
while not validMonth:
lookForMonth = input('What month, please? (number from 1 through 12):')
try:
validMonth = 1<=int(lookForMonth)<=12
except:
pass
sqlCmd = 'SELECT date FROM bookings WHERE SUBSTR(date,4,2)="%.2i"' % int(lookForMonth)
for row in conn.execute(sqlCmd):
print (row)
With this code, I am able to output the date of bookings for a particular month. However I want to output the total incomes for a particular month. What do I need to add so that this works out the total incomes for a particular month and outputs it? Any help would be gladly appreciated, thanks.
Replace one statement.
SELECT sum(income) FROM bookings where SUBSTR(date,4,2)='04'
As in:
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE TABLE bookings (date text, income real)')
c.execute('''INSERT INTO bookings VALUES ('01/04/2017', 19.22)''')
c.execute('''INSERT INTO bookings VALUES ('15/04/2017', 19.22)''')
c.execute('''INSERT INTO bookings VALUES ('22/04/2017', 19.22)''')
validMonth = False
while not validMonth:
lookForMonth = input('What month, please? (number from 1 through 12):')
try:
validMonth = 1<=int(lookForMonth)<=12
except:
pass
sql = '''SELECT sum(income) FROM bookings where SUBSTR(date,4,2)="%.2i"''' % int(lookForMonth)
for row in c.execute(sql):
print (row)
Resulting output:
What month, please? (number from 1 through 12):4
(57.66,)
First of all, you want to select both in your sql statement.
sqlCmd = 'SELECT date_of_booking,incomes FROM bookings WHERE SUBSTR(date,4,2)="%.2i"' % int(lookForMonth)
income_sum = 0
for (row_date, row_income) in conn.execute(sqlCmd):
income_sum += row_income
print row_date
print income_sum
Then you can specify both date and income of the row in your loop like above.

Get corresponding row properties for min value in column from database table

I have a MySQL table with the following data:
ID, PERSON_NAME, SCORE, DATE
I'm trying to write a query where I can get the minimum SCORE value and the corresponding PERSON_NAME value. I've tried the following query:
min_query = "SELECT PERSON_NAME, MIN(SCORE) FROM HTMLSCORES"
cursor.execute(min_query)
result = cursor.fetchone()
name = result[0]
min_score = result[1]
However, the name value is always the same and seems to be the first entry in the table. I would like to get the corresponding PERSON_NAME value for the MIN(SCORE). How do I go about writing that query?
Try this:
SELECT PERSON_NAME, SCORE
FROM HTMLSCORES
WHERE SCORE =
(SELECT MIN(SCORE)
FROM HTMLSCORES)
Look at the sub-query first. We can find the MIN score from your table using the MIN function. Then, in the main query, we select the row or rows where score in that row matches the sub-query score.
Your first attempt doesn't work because the query is looking at the person name and the score independently. Writing the query this way will link them together.
min_query = "SELECT PERSON_NAME, MIN(SCORE) AS 'Min_Score' FROM HTMLSCORES GROUP BY PERSON_NAME ORDER BY PERSON_NAME"
This will return a list of all PERSON_NAME and their min score.
If you are after a particular user and know what the PERSON_NAME should be use
pyPerson = 'Name Here'
min_query = "SELECT PERSON_NAME, MIN(SCORE) AS 'Min_Score' FROM HTMLSCORES WHERE PERSON_NAME = '" + str(pyPerson) + "' GROUP BY PERSON_NAME"
Forgive my crude python but it should work SQL wise.

Categories

Resources