Python + MySql Connectivity
Python + MySql Connectivity
1. Write a Python program that connects to a MySQL database named school. Create a
table called students with the following structure:
host = localhost, username = admin, password = 1234
Field Type
id INT
name VARCHAR(50)
age INT
grade VARCHAR(10)
Insert one record in the table after creation. Ensure that the table is created only if it
does not already exist.
import mysql.connector
try:
connection = mysql.connector.connect(
host = "localhost",
user = "Admin",
passwd = "1234",
database = "school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
insert_query = """
INSERT INTO students (name, age, grade)
VALUES ('John Doe', 16, '10th')
"""
cursor.execute(insert_query)
connection.commit()
print("One record inserted into 'students' table.")
finally:
# Close the connection
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
Output:
Connected to the database.
Table 'students' created or already exists.
One record inserted into 'students' table.
Database connection closed.
def AddAndDisplay():
import mysql.connector as mycon
mydb = mycon.connect(
host="localhost",
user="root",
passwd="Pencil",
database="ITEMDB"
)
mycur = mydb.cursor()
no = int(input("Enter Item Number: "))
nm = input("Enter Item Name: ")
pr = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
query = "INSERT INTO stationery VALUES ({}, '{}', {}, {})"
query = query.format(no, nm, pr, qty)
mycur.execute(query)
mydb.commit()
mycur.execute("SELECT * FROM stationery WHERE price > 120")
for rec in mycur:
print(rec)
mycur.close()
mydb.close()
Output:
Enter Item Number: 101
Enter Item Name: Notebook
Enter Price: 150
Enter Quantity: 20
3. Write a Python program to connect to a MySQL database and print the details of
employees belonging to a specific department provided by the user.
Use the following connection details for the database:
Host: localhost, User: root, Password: password123, Database: company_db
Table structure is as follows:
Field Type
employee_id varchar(5)
employee_name varchar(100)
department varchar(50)
import mysql.connector
def emp_dept(d_name):
connection = mysql.connector.connect(
host='localhost',
user='root',
passwd='password123',
database='company_db'
)
cursor = connection.cursor()
query = """SELECT employee_id, employee_name, department
FROM employees
WHERE department = '{}'""".format(d_name)
cursor.execute(query)
results = cursor.fetchall()
if results:
print("Employees in the",d_name, "department:")
for row in results:
print(row)
else:
print("No employee found in the",d_name,"deptartment")
cursor.close()
connection.close()
4. Write a Python program to connect to a MySQL database and fetch details of all
students enrolled in a specific course provided by the user.
Use the following connection details:
Host: localhost, User: root, Password: password123, Database: school_db
The table students has the following schema:
Field Type
student_id varchar(4)
student_name varchar(60)
course varchar(40)
import mysql.connector
def get_students(course):
conn = mysql.connector.connect(
host='localhost',
user='root',
passwd='password123',
database='school_db'
)
cur = conn.cursor()
query = """ SELECT student_id, student_name, course
FROM students
WHERE course = '{}' """.format(course)
cur.execute(query)
res = cur.fetchall()
if res:
print("Students in the",course,"course:")
for row in res:
print(row)
else:
print("No students found in the",course,’course")
cur.close()
conn.close()
Output:
Students in the 'Mathematics' course:
(1, 'Alice', 'Mathematics')
(3, 'Charlie', 'Mathematics')