0% found this document useful (0 votes)
7 views6 pages

21.mysql - Students. 1

The document is a Python program that demonstrates various SQL operations on a MySQL database, specifically for managing a 'student' table. It includes functions to drop, create, initialize, update, delete, and perform aggregate calculations (min, max, sum, average, count) on the student data. The program establishes a connection to the database, executes the defined operations, and then closes the connection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views6 pages

21.mysql - Students. 1

The document is a Python program that demonstrates various SQL operations on a MySQL database, specifically for managing a 'student' table. It includes functions to drop, create, initialize, update, delete, and perform aggregate calculations (min, max, sum, average, count) on the student data. The program establishes a connection to the database, executes the defined operations, and then closes the connection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

# Program to demonstrate various SQL operation on mysql db in Python

import mysql.connector
import json

tableName = "student"

# Establish a connection to the database


cnx = mysql.connector.connect(
user="root",
password="root",
host="localhost",
database="pps",
collation="utf8mb4_unicode_ci",
charset="utf8mb4",
)

# Drop student table if it exists


def dropTable():
query = f"DROP TABLE IF EXISTS {tableName};"

# Create a cursor object to execute queries


cursor = cnx.cursor()

# Execute query
cursor.execute(query)

result = cursor.fetchone()

# Close the cursor and connection


cursor.close()

# Create student table


def createTable():
query = f""" CREATE TABLE IF NOT EXISTS {tableName} (
student_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
age INT,
marks INT
);"""
# Create a cursor object to execute queries
cursor = cnx.cursor()

cursor.execute(query)

# Close the cursor and connection


cursor.close()

"""
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)

# Close the cursor and connection


cursor.close()

"""
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()

print(f"{cursor.rowcount} rows updated.")


# Close the cursor and connection
cursor.close()

"""
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]}")

# Close the cursor and connection


cursor.close()

"""
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]}")

# Close the cursor and connection


cursor.close()

"""
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]}")

# Close the cursor and connection


cursor.close()

"""
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]}")

# Close the cursor and connection


cursor.close()

"""
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]}")

# Close the cursor and connection


cursor.close()

def main():
dropTable()
createTable()

initDb()

updateDb()
deleteStudent()

calcMin()
calcMax()
calcSum()
calcAvg()
calcCount()

# Cleanup connectio
cnx.close()

main()

You might also like