Lesson 62 of 70 – Python Database Programming
89%

Python Database Programming

Python can be used to connect with databases, store data, retrieve records, update information, and delete records. Database programming is an important part of building real-world applications.

Note: Python can work with many databases such as MySQL, SQLite, PostgreSQL, Oracle and others.
What is a Database?

A database is an organized collection of data. It allows applications to store and manage information efficiently.

For example, a student management system may store student names, mobile numbers, courses and fees in a database.

Student Database

ID     Name       Course
1      Rahul      Python
2      Priya      Java
3      Amit       SQL
Why Use Databases with Python?

Databases are useful when an application needs to permanently store large amounts of information.

  • Store application data
  • Retrieve records
  • Update existing information
  • Delete records
  • Search data
  • Generate reports
  • Manage users and accounts
Popular Databases Used with Python

Python can work with several database systems:

  • MySQL
  • SQLite
  • PostgreSQL
  • Oracle Database
  • Microsoft SQL Server

The database you choose depends on the requirements of your application.

SQLite in Python

SQLite is a lightweight database that is included with Python through the built-in sqlite3 module.

It stores the complete database in a single file and does not require a separate database server.

import sqlite3

connection = sqlite3.connect("school.db")

print("Database connected")
Output:
Database connected
Creating a Database Connection

The sqlite3.connect() function is used to connect to an SQLite database.

import sqlite3

conn = sqlite3.connect("students.db")

print("Connected successfully")
Explanation:
  • sqlite3 imports the SQLite module.
  • connect() creates or opens the database.
  • students.db is the database file.
Creating a Cursor

A cursor is used to execute SQL statements and retrieve results from a database.

import sqlite3

conn = sqlite3.connect("students.db")

cursor = conn.cursor()

print("Cursor created")
Creating a Table

The SQL CREATE TABLE statement can be executed using the cursor.

import sqlite3

conn = sqlite3.connect("students.db")

cursor = conn.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY,
    name TEXT,
    course TEXT,
    fee INTEGER
)
""")

conn.commit()

print("Table created")
Output:
Table created
Inserting Data

The SQL INSERT statement is used to add records.

cursor.execute(
    "INSERT INTO students (name, course, fee) VALUES (?, ?, ?)",
    ("Rahul", "Python", 15000)
)

conn.commit()

The question marks are parameter placeholders used by SQLite.

Inserting Multiple Records

The executemany() method can be used to insert multiple records.

students = [
    ("Rahul", "Python", 15000),
    ("Priya", "Java", 18000),
    ("Amit", "SQL", 12000)
]

cursor.executemany(
    "INSERT INTO students (name, course, fee) VALUES (?, ?, ?)",
    students
)

conn.commit()
Reading Data

The SELECT statement is used to retrieve records from a table.

cursor.execute("SELECT * FROM students")

rows = cursor.fetchall()

for row in rows:
    print(row)
Example Output:
(1, 'Rahul', 'Python', 15000)
(2, 'Priya', 'Java', 18000)
(3, 'Amit', 'SQL', 12000)
fetchone()

The fetchone() method returns one record from the query result.

cursor.execute("SELECT * FROM students")

row = cursor.fetchone()

print(row)
Example Output:
(1, 'Rahul', 'Python', 15000)
fetchmany()

The fetchmany() method retrieves a specified number of records.

cursor.execute("SELECT * FROM students")

rows = cursor.fetchmany(2)

for row in rows:
    print(row)
fetchall()

The fetchall() method retrieves all remaining records from the query result.

cursor.execute("SELECT * FROM students")

rows = cursor.fetchall()

for row in rows:
    print(row)
WHERE Clause

The WHERE clause is used to retrieve records that satisfy a condition.

cursor.execute(
    "SELECT * FROM students WHERE course = ?",
    ("Python",)
)

rows = cursor.fetchall()

for row in rows:
    print(row)
Updating Data

The SQL UPDATE statement is used to modify existing records.

cursor.execute(
    "UPDATE students SET fee = ? WHERE id = ?",
    (18000, 1)
)

conn.commit()

The fee of the student whose ID is 1 is changed to 18000.

Deleting Data

The SQL DELETE statement is used to remove records.

cursor.execute(
    "DELETE FROM students WHERE id = ?",
    (3,)
)

conn.commit()

This deletes the student whose ID is 3.

Using Parameterized Queries

Parameterized queries allow values to be passed separately from SQL statements. They are safer than building SQL statements by concatenating user input.

name = "Rahul"

cursor.execute(
    "SELECT * FROM students WHERE name = ?",
    (name,)
)

rows = cursor.fetchall()
Important: Avoid directly joining untrusted user input into SQL strings. Use the parameter mechanism provided by the database driver.
Transactions and commit()

Changes such as INSERT, UPDATE and DELETE normally need to be committed before they are permanently saved.

cursor.execute(
    "UPDATE students SET fee = ? WHERE id = ?",
    (20000, 1)
)

conn.commit()

The commit() method saves the transaction.

rollback()

If an error occurs before a transaction is committed, rollback() can be used to undo the pending changes.

try:

    cursor.execute(
        "UPDATE students SET fee = ? WHERE id = ?",
        (25000, 1)
    )

    conn.commit()

except Exception:

    conn.rollback()

    print("Transaction rolled back")
Using try-except with Database Operations

Database operations can fail because of invalid SQL, missing tables, incorrect data or other database errors. Exception handling can be used to handle such problems.

import sqlite3

try:

    conn = sqlite3.connect("students.db")

    cursor = conn.cursor()

    cursor.execute("SELECT * FROM students")

    rows = cursor.fetchall()

    for row in rows:
        print(row)

except sqlite3.Error as error:

    print("Database error:", error)

finally:

    conn.close()
Closing the Database Connection

After completing database operations, the connection should be closed when it is no longer needed.

conn.close()

Closing connections helps release resources properly.

Complete SQLite Example
import sqlite3

conn = sqlite3.connect("school.db")

cursor = conn.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY,
    name TEXT,
    course TEXT,
    fee INTEGER
)
""")

cursor.execute(
    "INSERT INTO students (name, course, fee) VALUES (?, ?, ?)",
    ("Rahul", "Python", 15000)
)

conn.commit()

cursor.execute("SELECT * FROM students")

rows = cursor.fetchall()

for row in rows:
    print(row)

conn.close()
Using with for Database Connections

Python's context manager can help manage database transactions and resources. For SQLite, using with around the connection can automatically commit a successful transaction or roll it back if an exception occurs.

import sqlite3

with sqlite3.connect("school.db") as conn:

    cursor = conn.cursor()

    cursor.execute(
        "UPDATE students SET fee = ? WHERE id = ?",
        (18000, 1)
    )
Working with MySQL

Python can also connect to MySQL using a MySQL driver such as mysql-connector-python.

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="school"
)

print("MySQL connected")

For detailed MySQL programming, see the previous lesson: MySQL with Python.

Database CRUD Operations

CRUD is a common term used in database programming.

Operation SQL Command Purpose
Create INSERT Add new data
Read SELECT Retrieve data
Update UPDATE Modify existing data
Delete DELETE Remove data
Python Database Workflow

A typical database application follows these steps:

  1. Import the database module or driver.
  2. Create a database connection.
  3. Create a cursor when needed.
  4. Execute SQL statements.
  5. Fetch results for SELECT queries.
  6. Commit successful changes.
  7. Rollback when a transaction needs to be undone.
  8. Close resources when finished.
Common Database Mistakes
  • Forgetting to call commit() after changes.
  • Not closing database resources.
  • Writing invalid SQL statements.
  • Using incorrect table or column names.
  • Concatenating untrusted input into SQL statements.
  • Not handling database exceptions.
  • Forgetting to check transaction errors.
Real-World Applications

Python database programming is commonly used in applications such as:

  • Student Management Systems
  • Library Management Systems
  • Hospital Management Systems
  • Banking Applications
  • Inventory Management
  • E-commerce Websites
  • Employee Management Systems
  • Billing Systems
  • Learning Management Systems
  • Reporting Applications
Key Points
  • Python can connect to many database systems.
  • SQLite is available through Python's built-in sqlite3 module.
  • A database connection is used to communicate with the database.
  • A cursor executes SQL statements and retrieves results.
  • SELECT retrieves data.
  • INSERT adds data.
  • UPDATE modifies data.
  • DELETE removes data.
  • commit() saves transaction changes.
  • rollback() can undo pending transaction changes.
  • Parameterized queries should be used with external input.
  • Database errors should be handled using exception handling.
  • Database resources should be closed properly.

🧠 Quick Quiz

Question: Which SQL command is used to retrieve data from a database?