Database Operations in Python
Creating Tables, Insert, Update, Delete, Read and Transaction Control
Python can interact with databases using modules like sqlite3. It allows programmers to perform database operations such as creating tables, inserting records, updating data, deleting data, and reading records.
These operations are commonly called CRUD operations:
-
Create – Create tables and insert data
-
Read – Retrieve data from tables
-
Update – Modify existing records
-
Delete – Remove records from tables
Python also supports Transaction Control, which ensures database operations are completed safely.
1. Creating a Table
A table is created using the CREATE TABLE SQL command.
import sqlite3
conn = sqlite3.connect("college.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS student(
id INTEGER PRIMARY KEY,
name TEXT,
department TEXT
)
""")
conn.commit()
2. Insert Data
The INSERT statement is used to add records.
cursor.execute("INSERT INTO student (id, name, department) VALUES (1,'Arun','CS')")
conn.commit()
3. Read Data (SELECT)
Used to retrieve data from the table.
cursor.execute("SELECT * FROM student")
rows = cursor.fetchall()
for row in rows:
print(row)
Output Example:
(1, 'Arun', 'CS')
4. Update Data
Used to modify existing records.
cursor.execute("UPDATE student SET department='IT' WHERE id=1")
conn.commit()
5. Delete Data
Used to remove records from the table.
cursor.execute("DELETE FROM student WHERE id=1")
conn.commit()
6. Transaction Control
Transactions ensure that database operations are safely executed.
Important methods:
| Method | Purpose |
|---|---|
commit() | Save changes permanently |
rollback() | Undo changes if error occurs |
close() | Close database connection |
Example:
try:
cursor.execute("INSERT INTO student VALUES (2,'Ravi','ECE')")
conn.commit()
except:
conn.rollback()
Basic Python Program (CRUD Example)
import sqlite3
conn = sqlite3.connect("college.db")
cursor = conn.cursor()
# Create table
cursor.execute("CREATE TABLE IF NOT EXISTS student(id INTEGER, name TEXT, dept TEXT)")
# Insert data
cursor.execute("INSERT INTO student VALUES(1,'prasath','CS')")
# Read data
cursor.execute("SELECT * FROM student")
print(cursor.fetchall())
conn.commit()
conn.close()
Output Example
[(1, 'prasath', 'CS')]
Conclusion:
Python database modules allow easy implementation of table creation, data insertion, updating, deleting, reading, and transaction control, which are essential for database-driven applications.
Comments
Post a Comment