Database Programming in Python
Learn how Python programs can connect to databases, store data and work with database records.
What is Database Programming?
Database programming means using a programming language to create, read, update and delete data stored in a database.
Python provides modules and libraries that allow programs to connect to databases and execute SQL commands.
Database Programming Flow
Python Application
Sends commands and receives data.
Database Connection
Connects the application to the database.
Database
Stores and manages application data.
Result
Database returns the requested information.
Common Databases Used with Python
SQLite
A lightweight database included with Python.
MySQL
A popular relational database used in applications.
PostgreSQL
A powerful relational database used for many applications.
SQLite with Python
SQLite is a lightweight relational database. Python
provides the built-in sqlite3 module for
working with SQLite databases.
import sqlite3
connection = sqlite3.connect("students.db")
print("Database connected")
Output:
Database connected
Creating a Table
SQL can be used to create tables inside the database.
import sqlite3
connection = sqlite3.connect("students.db")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students
(
id INTEGER PRIMARY KEY,
name TEXT,
course TEXT
)
""")
connection.commit()
connection.close()
print("Table created")
Output:
Table created
Inserting Data
The SQL INSERT statement is used to add
records to a table.
import sqlite3
connection = sqlite3.connect("students.db")
cursor = connection.cursor()
cursor.execute(
"INSERT INTO students (name, course) VALUES (?, ?)",
("Rahul", "Python")
)
connection.commit()
connection.close()
print("Student inserted")
Output:
Student inserted
Reading Data
The SQL SELECT statement is used to
retrieve records from a table.
import sqlite3
connection = sqlite3.connect("students.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
connection.close()
Example Output:
(1, 'Rahul', 'Python')
(2, 'Priya', '.NET')
Updating Data
The SQL UPDATE statement is used to
modify existing records.
import sqlite3
connection = sqlite3.connect("students.db")
cursor = connection.cursor()
cursor.execute(
"UPDATE students SET course = ? WHERE id = ?",
("Python Full Stack", 1)
)
connection.commit()
connection.close()
print("Student updated")
Output:
Student updated
Deleting Data
The SQL DELETE statement is used to
remove records from a table.
import sqlite3
connection = sqlite3.connect("students.db")
cursor = connection.cursor()
cursor.execute(
"DELETE FROM students WHERE id = ?",
(1,)
)
connection.commit()
connection.close()
print("Student deleted")
Output:
Student deleted
CRUD Operations
Most database applications perform four basic operations.
Create
Add new records.
Read
Retrieve records.
Update
Modify records.
Delete
Remove records.
Parameterized Queries
Parameterized queries allow values to be safely passed to SQL statements.
name = "Rahul"
course = "Python"
cursor.execute(
"INSERT INTO students (name, course) VALUES (?, ?)",
(name, course)
)
This approach is preferred when inserting user-provided values into SQL statements.
Example 👀📩
The following example creates a database, inserts a student and reads the stored data.
import sqlite3
connection = sqlite3.connect("college.db")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students
(
id INTEGER PRIMARY KEY,
name TEXT,
course TEXT
)
""")
cursor.execute(
"INSERT INTO students (name, course) VALUES (?, ?)",
("Amit", "Python")
)
connection.commit()
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()
for student in students:
print(student)
connection.close()
Advantages of Database Programming
Data Storage
Data can be stored permanently in a database.
Data Management
Applications can create, read, update and delete data.
Applications
Databases are used by many real-world software applications.
Best Practices
Close Connections
Close database connections after operations.
Use Parameters
Use parameterized queries for input values.
Commit Changes
Commit INSERT, UPDATE and DELETE operations.
Common Mistakes
- Forgetting to close the database connection.
-
Forgetting to call
commit()after modifying data. - Writing SQL queries incorrectly.
- Building SQL statements directly from user input.
Practice Programs
- Create an SQLite database using Python.
- Create a students table.
- Insert five student records.
- Display all student records.
- Update a student record.
- Delete a student record.
Summary
Database programming allows Python applications to
communicate with databases and manage stored data.
Python provides the sqlite3 module for
SQLite databases. Common database operations include
creating tables, inserting data, reading records,
updating records and deleting records.