asdasd
asdasd
Topic: Program to demonstrate CRUD (create, read, update and delete) operations
ondatabase (SQLite/ MySQL) using python.
Moodle MY SQL:
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
The execute() methods run the SQL query and return the result.
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
The execute() methods run the SQL query and return the result.
Experiments:
PERFORM THE FOLLOWING EXERCISE ON BOTH SQLITE
AND MySQL.
1. Write a Python program to list the tables of given SQLite database file.
6. Write python code to create Primary key – foreign key relation between two
tables
DELIVERABLES:
import MySQLdb
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
# 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)''')
# Commit changes
conn.commit()
print("Students Table:")
for row in rows:
print(row)
Write a Python program to insert a list of records into a given SQLite ta-
ble.
import MySQLdb
# List of records to
insert students_data = [
("Alice", 20, "A"),
("Bob", 22, "B"),
("Charlie", 21, "A"),
("David", 23, "C"),
]
# Commit changes
conn.commit()
print("Students Table:")
for row in rows:
print(row)
# Commit changes
conn.commit()
print("\nStudents Table:")
for row in rows:
print(row)
import MySQLdb
# Commit changes
conn.commit()
Write python code to create Primary key – foreign key relation between two
tables
import MySQLdb
# Commit changes
conn.commit()
import MySQLdb
# Commit changes
conn.commit()
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