Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

MySQL Python Programs 1

Uploaded by

patrunikhushi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

MySQL Python Programs 1

Uploaded by

patrunikhushi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PROGRAM NO.

1
Write a Python program that connects to a MySQL database, creates a stud table if it doesn't
exist, and allows the user to insert multiple student records (name, regno, section) into the table
and close the connection after committing the changes.

import mysql.connector as msc

# Establishing the connection


connection = msc.connect(host="localhost", database="mydb", user="root", passwd="1234")

if connection.is_connected():
print("Connection established successfully!")
else:
print("Connection failed!")

cursor = connection.cursor()

# Create the table if it doesn't exist


cursor.execute("CREATE TABLE IF NOT EXISTS stud (name VARCHAR(10), regno INT PRIMARY
KEY, section VARCHAR(5));")

# Taking the number of records from the user


n = int(input("Enter the number of records: "))

# Inserting records
for i in range(n):
print("Enter the details of student no: "+str(i + 1))

name = input("Enter the name: ")


regno = int(input("Enter the regno: "))
section = input("Enter the section: ")

# Using parameterized queries to prevent SQL injection


query = "INSERT INTO stud (name, regno, section) VALUES (%s, %s, %s);"
cursor.execute(query, (name, regno, section))

# Committing the transaction


connection.commit()
print("Data successfully added to the table.")

# Closing resources
cursor.close()
connection.close()
print("Connection closed.")
Output:
Connection established successfully!
Enter the number of records: 3
Enter the details of student no: 1
Enter the name: Anil
Enter the regno: 100
Enter the section: 12a
Enter the details of student no: 2
Enter the name: Bharath
Enter the regno: 101
Enter the section: 12b
Enter the details of student no: 3
Enter the name: Charan
Enter the regno: 102
Enter the section: 12e
Data successfully added to the table.
Connection closed.
PROGRAM NO. 2
Write a Python program that connects to a MySQL database, creates a table, inserts multiple
rows based on user input, adds a new column for "gender", and updates the column values
accordingly.

import mysql.connector as msc

# Establishing the connection


connection = msc.connect(host="localhost", database="mydb", user="root", passwd="1234")

if connection.is_connected():
print("Connection established successfully!")
else:
print("Connection failed")

cursor = connection.cursor()

# Create the table if it doesn't exist


cursor.execute("CREATE TABLE IF NOT EXISTS stud (name VARCHAR(10), regno INT PRIMARY
KEY, section VARCHAR(5));")

# Taking the number of records from the user


n = int(input("Enter the number of records: "))

# Inserting records
for i in range(n):
print("Enter the details of student no: "+str(i + 1))
name = input("Enter the name: ")
regno = int(input("Enter the regno: "))
section = input("Enter the section: ")

# Using parameterized queries to prevent SQL injection


query = "INSERT INTO stud (name, regno, section) VALUES (%s, %s, %s);"
cursor.execute(query, (name, regno, section))

# Committing the transaction


connection.commit()
print("Data successfully added to the table.")

# Adding the 'gender' column if it doesn't already exist


cursor.execute("ALTER TABLE stud ADD gender VARCHAR(6);")

# Retrieving all data from the table


cursor.execute("SELECT name, regno FROM stud;")
students = cursor.fetchall()

# Collecting gender information for each student


for student in students:
name = student[0]
st = "Enter the gender of "+name+": "
gender = input(st)
# Using parameterized query for updating the gender
cursor.execute("UPDATE stud SET gender = %s WHERE name = %s;", (gender, name))

# Committing the changes


connection.commit()

# Closing the connection


cursor.close()
connection.close()
print("Data successfully updated in the table.")

Output:
Connection established successfully!
Enter the number of records: 3
Enter the details of student no: 1
Enter the name: Bhanu
Enter the regno: 10
Enter the section: 9a
Enter the details of student no: 2
Enter the name: Rana
Enter the regno: 11
Enter the section: 9b
Enter the details of student no: 3
Enter the name: Chandru
Enter the regno: 15
Enter the section: 9e
Data successfully added to the table.
Enter the gender of Bhanu: Female
Enter the gender of Rana: Male
Enter the gender of Chandru: Male
Data successfully updated in the table.
PROGRAM NO. 3
Write a Python program to connect to a MySQL database, display all records from a specified
table, and allow the user to delete a record based on a given identifier (e.g., regno or name).

import mysql.connector as msc

# Establishing the connection


connection = msc.connect(host="localhost", database="mydb", user="root", passwd="1234")

if connection.is_connected():
print("Connection established successfully!")
else:
print("Connection Failed")

cursor = connection.cursor()

# Fetching and displaying records from the emp table


cursor.execute("SELECT * FROM emp;")
data = cursor.fetchall()

print("Records of employee table are:")


print("Name\tID\tDeptID\tSalary")
for record in data:
for field in record:
print(field, end="\t")
print() # To print a newline after each record

# Getting user input to delete a record


reg = int(input("\nEnter the ID of the record to be deleted: "))

# Checking if the ID exists


cursor.execute("SELECT * FROM emp WHERE id = %s;", (reg,))
result = cursor.fetchone()

if result:
# Deleting the record using parameterized query
delete_query = "DELETE FROM emp WHERE id = %s;"
cursor.execute(delete_query, (reg,))

# Committing the deletion


connection.commit()

# Fetching and displaying the updated records


cursor.execute("SELECT * FROM emp;")
data = cursor.fetchall()

print("\nAfter deletion, records of employee table are:")


print("Name\tID\tDeptID\tSalary")
for record in data:
# Printing each record without using join
for field in record:
print(field, end="\t")
print() # To print a newline after each record
else:
print("Record with ID "+str(reg)+" not found. Try again!")

# Closing the connection


cursor.close()
connection.close()

Output:
Connection established successfully!
Records of employee table are:
Name ID DeptID Salary
Alice 101 1 50000.00
Bob 102 2 60000.00
Charlie 103 1 70000.00
David 104 3 55000.00
Eve 105 2 75000.00

Enter the ID of the record to be deleted: 104

After deletion, records of employee table are:


Name ID DeptID Salary
Alice 101 1 50000.00
Bob 102 2 60000.00
Charlie 103 1 70000.00
Eve 105 2 75000.00

If the entered ID is not found in the table,


Enter the ID of the record to be deleted: 100
Record with ID 100 not found. Try again!
PROGRAM NO. 4
Write a Python program to connect to a MySQL database, display the records of a table, and
allow the user to update specific record(s) based on their input.

import mysql.connector as msc

# Establishing the connection


connection = msc.connect(host="localhost", database="mydb", user="root", passwd="1234")

if connection.is_connected():
print("Connection established successfully!")
else:
print("Connection Failed")

cursor = connection.cursor()

# Fetching and displaying records from the emplo table


cursor.execute("SELECT * FROM emplo;")
data = cursor.fetchall()

print("Records of employees are:")


print("EmpNo.\tName\tDOB\t\tQualification")
for record in data:
# Printing each record using .format()
print("{}\t{}\t{}\t{}".format(record[0], record[1], record[2], record[3]))

# Getting user input to update a record


eno = int(input("\nEnter the empno of the record to be updated: "))
newQ = input("Enter the new qualification of this employee: ")

# Checking if the entered empno exists


cursor.execute("SELECT * FROM emplo WHERE empno = %s;", (eno,))
existing_record = cursor.fetchone()

if existing_record:
# Updating the record using parameterized query
update_query = "UPDATE emplo SET qualification = %s WHERE empno = %s;"
cursor.execute(update_query, (newQ, eno))
connection.commit()
print("Record updated successfully.")
# Fetching and displaying the updated records
cursor.execute("SELECT * FROM emplo;")
data = cursor.fetchall()

print("\nAfter updation, records of employees are:")


print("EmpNo.\tName\tDOB\t\tQualification")
for record in data:
# Printing each record using .format()
print("{}\t{}\t{}\t{}".format(record[0], record[1], record[2], record[3]))
else:
print("Error: Employee with empno "+str(eno)+" does not exist. Try again.")
# Closing the connection
cursor.close()
connection.close()

Output:
Connection established successfully!
Records of employees are:
EmpNo. Name DOB Qualification
101 John 1990-05-15 B.Sc
102 Alice 1985-03-20 M.Sc
103 Bob 1987-11-10 Ph.D
104 David 1992-07-25 B.Com
105 Eva 1989-12-30 MBA

Enter the empno of the record to be updated: 102


Enter the new qualification of this employee: BCA
Record updated successfully.

After updation, records of employees are:


EmpNo. Name DOB Qualification
101 John 1990-05-15 B.Sc
102 Alice 1985-03-20 BCA
103 Bob 1987-11-10 Ph.D
104 David 1992-07-25 B.Com
105 Eva 1989-12-30 MBA

If the entered empno is not found in the table,


Enter the empno of the record to be updated: 111
Error: Employee with empno 111 does not exist. Try again.

You might also like