Problem iterating through MySQL in python - 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

Related

Update a table's column by using a group by

I would like to calculate the average in specific column of my table grouping by another column, but it doesn't work, I have a problem whith the group by.
My code:
import sqlite3
conn = sqlite3.connect("ma_base.db")
cur = conn.cursor()
cur.execute("UPDATE test_centrale set avg_price = avg(prix) group by test_centrale.version ")
conn.commit()
print('done')
cur.close()
If I got your question right. Use subquery to find the second average and update using following query
cur.execute("UPDATE test_centrale set avg_price = (select avg(prix) from test_centrale group by test_centrale.version )")

SQL database query - return records which have all values from a list (Python)

I've managed to query and get results for values from a list. But say i have the genres ["Action", "Comedy", "Romance"] in the list I am using to query. My code below returns all the records which are action, romance and comedy whereas I want it to return only the records that meet all three genres. How can I do this?
The database has a field called genre in which there are multiple genres for each record.
Code:
with sqlite3.connect("animeData.db") as db: #anime database
c = db.cursor()
c.execute("select * from t where genre in %s" % repr(self.genreResults).replace('[','(').replace(']',')') ) #self.genreResults is the list containing the genres i want to query
results = c.fetchall()
print(results)
db.commit()
db.close()
Output:
Database:
It's returning all animes which have genres of action and adventure whereas I only want it to return animes which have both. Any suggestions?
If I understand correctly, 'like' clauses meet your requirements but you don't know how to convert list to 'like' clauses.
So the codes will be like below:
import sqlite3
with sqlite3.connect("animeData.db") as db: #anime database
c = db.cursor()
#self.genreResults is the list containing the genres i want to query
user_input = self.genreResults # for example: ['Action','Drama']
convert_to_like_conditions = ' and '.join(list(map(lambda item : "genre like '%{0}%'".format(item), user_input)))
print(convert_to_like_conditions) #Output: genre like '%Action%' and genre like '%Drama%'
c.execute("select * from t where %s" % convert_to_like_conditions )
results = c.fetchall()
print(results)
db.commit()
You can refer to the documents on map, string join.
And you probably notice I removed the last line (db.close) of your codes, you can refer to Understanding Python's "with" statement.

How can I update rows obtained by a SELECT query in PostgreSQL with Python? Python 2.7 psycopg2

I have the following code to calculate a value in specific rows of my table:
cursor.execute("SELECT * FROM restaurants WHERE license_type_code='20' ORDER BY general_score DESC;")
group_size = cursor.rowcount
for record in cursor:
index = cursor.rownumber
percentile = 100*(index - 0.5)/group_size
print percentile
What I need to do is to add the percentile result to the respective column score_percentile of each record I got with the SELECT query.
I thought about an UPDATE query like this:
cursor.execute("UPDATE restaurants SET score_percentile="+str(percentile)+" WHERE license_type_code IN (SELECT * FROM restaurants WHERE license_type_code='20' ORDER BY general_score DESC)")
But I don't know if that query is correct or if there's a more efficient and less silly way to do that (I'm sure there has to be).
Could you help me, please?
I'm new with SQL so any help or advice is highly appreciated.
Thanks!
You don't need the loop at all. Just one update query
cursor.execute("UPDATE restaurants SET score_percentile = 100*(rownumber - 0.5)/group_size FROM (SELECT COUNT (*) as group_size FROM restaurants WHERE license_type_code='20') as t WHERE restaurants.license_type_code='20'")
As Thomas said, I just needed an update query with the following syntax:
cursor.execute("UPDATE restaurants f SET score_percentile = ROUND(100*(f2.rownumber - 0.5)/"+str(group_size)+",3) FROM (SELECT f2.*,row_number() OVER (ORDER BY general_score DESC) as rownumber FROM restaurants f2 WHERE license_type_code='20') f2 WHERE f.license_type_code='20' AND f2.license_number=f.license_number;")
And I got the group_size by:
cursor.execute("SELECT COUNT(*) FROM restaurants WHERE license_type_code='20'")
group_size = cursor.fetchone()
group_size = group_size[0]
That worked perfect for my case

How to stream/print the several last appended data from a table in SQL Server using python?

I have a table in my SQL Server that is being updated every minute.
Currently, I get the data from my table using this lines of code:
conn = pymssql.connect(server, user, password, "tempdb")
def print_table():
cursor = conn.cursor(as_dict=True)
cursor.execute('SELECT * FROM EmotionDisturbances WHERE name=%s', 'John Doe')
for row in cursor:
#Show the data:
print("rate=%d, emotion=%s" % (row['rate'], row['emotion']))
conn.close()
In my application, I run this the function every 10 seconds.
How do I update the function so that I only print the last appended data from my table?
Thanks
Assuming you have an auto-incrementing index in column id you'd do:
SELECT * FROM EmotionDisturbances WHERE name = % ORDER BY id DESC LIMIT 1
EDIT: If you want all data that was added after a certain time, then you'll need to migrate your schema to have a created date column if it doesn't have one already, then you can do:
SELECT *
FROM EmotionDisturbances
WHERE name = % AND created >= DATEADD(second, -10, GETDATE())
This would get all of the records created over the last 10 seconds, since you said this function runs every 10 seconds.

Select rows from one table where certain field is equal to a field in a row from another table, with Python and SQLite3

I have a small database which is legacy from an almost defunct project. This database has a "Patients" table with individual personal data and an unique "Id" field, and an "Exams" table with some fields for each exam, one of these fields being "Patient_Id".
What I want is, for a given patient (row from "Pacientes" table) the exams (rows) from "Exames" table whose "Patient_Id" matches that of the given patient.
I am very beginner with SQL, so if the question is very naive, I apologize.
My working code is the following, but I am using a for loop while I would much rather have a SQL query (which is the very point of using databases, I think...):
#!/usr/bin/env python
# coding: utf-8
import os, sqlite3
conn = sqlite3.connect('BDdata.db3')
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('SELECT * FROM Exames')
exams = c.fetchall()
c.execute('SELECT * FROM Pacientes')
for row in c:
Nome = row['nome']
ID = row['Id']
for exam in exams: # I would like to replace this loop
if exam['Id_Paciente'] == ID: # with a SQL query meaning
print exam['File']
============================
An answer to a similar question seems to be what I want, but I have no idea how to do this in Python with sqlite3 module, much less what in this expression is essential and what is incidental, or what is the syntax structure:
Selecting rows from a table by One a field from other table
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)
I think the following should do what you want:
...
c = conn.cursor()
c.execute('SELECT * FROM Pacientes')
for row in c.fetchall():
Nome = row['nome']
ID = row['Id']
c.execute('SELECT File FROM Exames WHERE Id_Paciente=?', [ID])
for exam in c:
print exam['File']

Categories

Resources