0% found this document useful (0 votes)
3 views14 pages

asdasd

This document outlines an experiment focused on demonstrating CRUD operations using Python with SQLite and MySQL databases. It includes prerequisites, objectives, and a step-by-step procedure for creating, reading, updating, and deleting records in a database. Additionally, it provides code examples and exercises to reinforce learning outcomes related to database connectivity and SQL operations in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

asdasd

This document outlines an experiment focused on demonstrating CRUD operations using Python with SQLite and MySQL databases. It includes prerequisites, objectives, and a step-by-step procedure for creating, reading, updating, and deleting records in a database. Additionally, it provides code examples and exercises to reinforce learning outcomes related to database connectivity and SQL operations in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Experiment No: 7

Topic: Program to demonstrate CRUD (create, read, update and delete) operations
ondatabase (SQLite/ MySQL) using python.

Prerequisite: Knowledge of some programming language like C, Java

Mapping With COs: CSL405.2

Objective: Ability to write program by implementing Object Oriented concepts


in python. Understanding the connection API to databases in Python

Outcome: To Learn to install MySql


To learn how to connect SQLite , MYSQL , DICTIONARY to python.
To learn how to perform DDL , DML and DCL SQL statements in Python.
Bloom’s Taxonomy : Apply

Theory/ Steps/ 1. Create a Python project in Pycharm


Algorithm/ 2. Create a database and a tables in MySQL
Procedure: 3. Create new record
4. Read Data
5. Update existing record
6. Delete data
7. Perform DDL, DML , DCL operations and joins on the
created Database.

Above seven steps to be performed for both SQLite and MYSQL.

Refer the Theory Content folder and Programs on

Moodle MY SQL:

How to Connect to MySQL Database in Python

1. Install MySQL connector module

Use the pip command to install MySQL connector Python.


pip install mysql-connector-python ( requires MySql to be already installed )

2. Import MySQL connector module

Import using a import mysql.connector statement so you can use this


module’s methods to communicate with the MySQL database.

3. Use the connect() method

Use the connect() method of the MySQL Connector class with the
required arguments to connect MySQL. It would return a MySQLCon-
nectionobject if the connection established successfully

4. Use the cursor() method


Use the cursor() method of a MySQLConnectionobject to create
a cursor object to perform various SQL operations.

5. Use the execute() method

The execute() methods run the SQL query and return the result.

6. Extract result using fetchall()

Use cursor.fetchall() or fetchone() or fetchmany() to readquery result.

7. Close cursor and connection objects

use cursor.clsoe() and connection.clsoe() method to closeopen connections


after your work completes

How to Connect to MySQL Database in Python

1. Install MySQL connector module

Use the pip command to install MySQL connector Python. pip


install mysql-connector-python

2. Import MySQL connector module

Import using a import mysql.connectorstatement so you can usethis


module’s methods to communicate with the MySQL database.

3. Use the connect() method

Use the connect() method of the MySQL Connector class with the
required arguments to connect MySQL. It would return a MySQLCon-
nectionobject if the connection established successfully

4. Use the cursor() method

Use the cursor() method of a MySQLConnectionobject to create


acursor object to perform various SQL operations.

5. Use the execute() method

The execute() methods run the SQL query and return the result.

6. Extract result using fetchall()

Use cursor.fetchall() or fetchone() or fetchmany() to readquery result.


7. Close cursor and connection objects

use cursor.clsoe() and connection.clsoe() method to closeopen connections


after your work completes

Experiments:
PERFORM THE FOLLOWING EXERCISE ON BOTH SQLITE
AND MySQL.

1. Write a Python program to list the tables of given SQLite database file.

2. Write a Python program to create a table and insert some records in


that table. Finally selects all rows from the table and display the
records.

3. Write a Python program to insert a list of records into a given SQLite


ta- ble.

4. Write a Python program to insert values to a table from user input.

5. Write a Python program to update a specific column value of a


given table and select all rows before and after updating the said
table.

6. Write python code to create Primary key – foreign key relation between two
tables

7. Write Python code to perform a simple join on two tables

8. Write python code to create index on tables

DELIVERABLES:

1. Code for each exercise question and then screen shot.


Write a Python program to list the tables of given SQLite database file.

import MySQLdb

# Create the connection object


myconn = MySQLdb.connect(
host="localhost", user="root",
passwd="Himu@3108"
)

# Create the cursor object cur


= myconn.cursor()

# Execute the query


cur.execute("SHOW DATABASES")

# Display the result for


x in cur:
print(x)

# Close the connection


myconn.close()

Write a Python program to create a table and insert some records in that
table. Finally selects all rows from the table and display the records.

import MySQLdb

# Connect to MySQL database conn


= MySQLdb.connect(
host="localhost", user="root",
passwd="Himu@3108",
db="train"
)
cursor = conn.cursor()

# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
grade VARCHAR(10) NOT NULL)''')

# Insert some records


students_data = [
("Alice", 20, "A"),
("Bob", 22, "B"),
("Charlie", 21, "A"),
]
cursor.executemany("INSERT INTO students (name, age, grade) VALUES (%s, %s,
%s)", students_data)

# Commit changes
conn.commit()

# Select and display all rows


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()

print("Students Table:")
for row in rows:
print(row)

# Close the connection


cursor.close()
conn.close()

Write a Python program to insert a list of records into a given SQLite ta-
ble.

import MySQLdb

# Connect to MySQL database


conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="Himu@3108",
db="train"
)
cursor = conn.cursor()

# Create a table if it doesn't exist


cursor.execute('''CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
grade VARCHAR(10) NOT NULL)''')

# List of records to
insert students_data = [
("Alice", 20, "A"),
("Bob", 22, "B"),
("Charlie", 21, "A"),
("David", 23, "C"),
]

# Insert multiple records


cursor.executemany("INSERT INTO students (name, age, grade)
VALUES (%s, %s, %s)", students_data)

# Commit changes
conn.commit()

# Select and display all rows


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()

print("Students Table:")
for row in rows:
print(row)

# Close the connection


cursor.close()
conn.close()
Write a Python program to insert values to a table from user input
import MySQLdb

# Connect to MySQL database


conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="Himu@3108",
db="train"
)
cursor = conn.cursor()

# Create table if it doesn't exist


cursor.execute('''CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
grade VARCHAR(10) NOT NULL)''')

# Take user input


name = input("Enter student name:
") age = int(input("Enter student age:
")) grade = input("Enter student
grade: ")

# Insert user input into table


cursor.execute("INSERT INTO students (name, age, grade) VALUES (%s, %s,
%s)", (name, age, grade))

# Commit changes
conn.commit()

# Select and display all rows


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()

print("\nStudents Table:")
for row in rows:
print(row)

# Close the connection


cursor.close()
conn.close()
Write a Python program to update a specific column value of a given
table and select all rows before and after updating the said table.

import MySQLdb

# Connect to MySQL database


conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="Himu@3108",
db="train"
)
cursor = conn.cursor()

# Create table if it doesn't exist


cursor.execute('''CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
grade VARCHAR(10) NOT NULL)''')

# Select and display all rows before update print("\


nBefore Update:")
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)

# Take user input for update


student_id = int(input("\nEnter student ID to update grade: "))
new_grade = input("Enter new grade: ")

# Update the specific column


cursor.execute("UPDATE students SET grade = %s WHERE id = %s",
(new_grade, student_id))

# Commit changes
conn.commit()

# Select and display all rows after update print("\


nAfter Update:")
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)

# Close the connection


cursor.close()
conn.close()

Write python code to create Primary key – foreign key relation between two
tables

import MySQLdb

# Connect to MySQL database


conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="Himu@3108",
db="train"
)
cursor = conn.cursor()

# Enable foreign key support (optional, usually enabled by default)


cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")

# Create 'departments' table (Parent table)


cursor.execute('''CREATE TABLE IF NOT EXISTS departments (
dept_id INT AUTO_INCREMENT PRIMARY KEY,
dept_name VARCHAR(255) NOT NULL)''')

# Create 'employees' table (Child table with Foreign Key)


cursor.execute('''CREATE TABLE IF NOT EXISTS employees (
emp_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ON
DELETE CASCADE ON UPDATE CASCADE)''')

print("Tables 'departments' and 'employees' created successfully.")

# Insert sample data into departments (if not already present)


cursor.execute("INSERT INTO departments (dept_name) VALUES ('HR'), ('IT'),
('Finance') ON DUPLICATE KEY UPDATE dept_name=VALUES(dept_name);")

# Insert sample data into employees (if not already present)


cursor.execute("INSERT INTO employees (name, age, dept_id) VALUES ('Alice',
25, 1), ('Bob', 30, 2), ('Charlie', 28, 3) ON DUPLICATE KEY UPDATE
name=VALUES(name), age=VALUES(age), dept_id=VALUES(dept_id);")

# Commit changes
conn.commit()

# Display all records from 'departments' table print("\


nDepartments Table:")
cursor.execute("SELECT * FROM departments")
departments = cursor.fetchall()
for dept in departments:
print(dept)

# Display all records from 'employees' table print("\


nEmployees Table:")
cursor.execute("SELECT * FROM employees")
employees = cursor.fetchall()
for emp in employees:
print(emp)

# Close the connection


cursor.close()
conn.close()
Write Python code to perform a simple join on two tables

import MySQLdb

# Connect to MySQL database


conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="Himu@3108",
db="train"
)
cursor = conn.cursor()

# Enable foreign key support (optional, usually enabled by default)


cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")

# Create 'departments' table (Parent table)


cursor.execute('''CREATE TABLE IF NOT EXISTS departments (
dept_id INT AUTO_INCREMENT PRIMARY KEY,
dept_name VARCHAR(255) NOT NULL)''')

# Create 'employees' table (Child table with Foreign Key)


cursor.execute('''CREATE TABLE IF NOT EXISTS employees (
emp_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ON
DELETE CASCADE ON UPDATE CASCADE)''')

print("Tables 'departments' and 'employees' created successfully.")

# Insert sample data into departments


cursor.execute("INSERT IGNORE INTO departments (dept_id, dept_name)
VALUES (1, 'HR'), (2, 'IT'), (3, 'Finance');")

# Insert sample data into employees


cursor.execute("INSERT IGNORE INTO employees (emp_id, name, age,
dept_id) VALUES (1, 'Alice', 25, 1), (2, 'Bob', 30, 2), (3, 'Charlie', 28, 3);")

# Commit changes
conn.commit()

# Perform JOIN operation to get employee names with department names


cursor.execute('''SELECT employees.emp_id, employees.name, employees.age,
departments.dept_name
FROM employees
JOIN departments ON employees.dept_id = departments.dept_id''')

# Fetch and display results


print("\nEmployees with Department Names:")
rows = cursor.fetchall()
for row in rows:
print(row)

# Close the connection


cursor.close()
conn.close()

Write python code to create index on tables


import MySQLdb

# Connect to MySQL database


myconn = MySQLdb.connect(
host="localhost",
user="root",
passwd="Himu@3108",
db="train"
)
cur = myconn.cursor()

# Function to check if an index exists


def index_exists(table_name, index_name):
cur.execute(f"SHOW INDEX FROM {table_name} WHERE Key_name =
'{index_name}';")
return cur.fetchone() is not None # Returns True if index exists

# Create index on employees table (if it doesn't exist)


if not index_exists("employees", "idx_employee_name"):
cur.execute("CREATE INDEX idx_employee_name ON employees(name)")
print("Index 'idx_employee_name' created on employees table.")
else:
print("Index 'idx_employee_name' already exists on employees table.")

# Create index on departments table (if it doesn't exist)


if not index_exists("departments", "idx_department_name"):
cur.execute("CREATE INDEX idx_department_name ON
departments(dept_name)")
print("Index 'idx_department_name' created on departments table.")
else:
print("Index 'idx_department_name' already exists on
departments table.")

# Show Indexes from employees table


cur.execute("SHOW INDEX FROM employees")
print("\nIndexes on employees Table:")
for row in cur.fetchall():
print(row)
# Show Indexes from departments table
cur.execute("SHOW INDEX FROM
departments") print("\nIndexes on
departments Table:")
for row in cur.fetchall():
print(row)

# Close the connection


myconn.close()

Conclusion: Ability to connect to data bases through Python and perform DDL , DCL and
DML Operations from Python.
References: https://pynative.com/python-mysql-database-connection/

elearn.dbit.in

You might also like