21.mysql - Students. 1
21.mysql - Students. 1
import mysql.connector
import json
tableName = "student"
# Execute query
cursor.execute(query)
result = cursor.fetchone()
cursor.execute(query)
"""
Initialize db by inserting dummy values
"""
def initDb():
query = f""" INSERT INTO {tableName} (student_id, first_name,
last_name, age, marks)
VALUES
(1, 'Raju', 'V', 18, 85),
(2, 'Amit', 'S', 19, 92),
(3, 'Hema', 'J', 20, 78),
(4, 'Rita', 'W', 18, 95);
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
"""
Update a tuple in db
"""
def updateDb():
query = f""" UPDATE {tableName}
SET marks=90
WHERE student_id=4;
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
print(f"{cursor.rowcount} rows updated.")
# Close the cursor and connection
cursor.close()
"""
Delete a tuple from table
"""
def deleteStudent():
query = f""" DELETE FROM {tableName}
WHERE student_id=3;
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
# Check the result of the query
result = cursor.fetchone()
"""
Find min marks in table
"""
def calcMin():
query = f""" SELECT MIN(marks) as `min marks`
FROM {tableName};
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
# Check the result of the query
result = cursor.fetchone()
if result:
print(f"Min - {result[0]}")
"""
Find max marks in table
"""
def calcMax():
query = f""" SELECT MAX(marks) as `max marks`
FROM {tableName};
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
# Check the result of the query
result = cursor.fetchone()
if result:
print(f"Max - {result[0]}")
"""
Find sum of marks in table
"""
def calcSum():
query = f""" SELECT SUM(marks) as `sum marks`
FROM {tableName};
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
# Check the result of the query
result = cursor.fetchone()
if result:
print(f"Sum - {result[0]}")
"""
Find average marks in table
"""
def calcAvg():
query = f""" SELECT AVG(marks) as `avg marks`
FROM {tableName};
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
# Check the result of the query
result = cursor.fetchone()
if result:
print(f"Avg - {result[0]}")
"""
Find count of all tuples table
"""
def calcCount():
query = f""" SELECT COUNT(*) as `count`
FROM {tableName};
"""
# Create a cursor object to execute queries
cursor = cnx.cursor()
cursor.execute(query)
# Check the result of the query
result = cursor.fetchone()
if result:
print(f"Count - {result[0]}")
def main():
dropTable()
createTable()
initDb()
updateDb()
deleteStudent()
calcMin()
calcMax()
calcSum()
calcAvg()
calcCount()
# Cleanup connectio
cnx.close()
main()