Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

4.4 Database Connectivity & SQL

Lesson 28 of 32 in the free Data Visualisation and Analytics notes on Siksha Sarovar, written by Rohit Jangra.

Database Access in Python: The DB-API

1. Introduction to DB-API

Python provides a standard interface called DB-API 2.0 (PEP 249) for interacting with databases. This means the code structure looks almost identical whether you use SQLite, MySQL, or PostgreSQL.

Common Database Modules:

DatabasePython ModuleTypeInstallation
SQLitesqlite3File-based, serverlessBuilt-in (no install needed)
MySQLmysql.connectorClient-serverpip install mysql-connector-python
PostgreSQLpsycopg2Client-serverpip install psycopg2
MongoDBpymongoNoSQL (Document-based)pip install pymongo

2. The Connectivity Workflow (5-Step Lifecycle)

Every database interaction follows this pattern:

StepActionCodeNotes
1Connectconn = sqlite3.connect('db.sqlite')Creates file if not exists (SQLite)
2Cursorcursor = conn.cursor()The "pointer" that executes queries
3Executecursor.execute("SQL query")Runs the SQL statement
4Commitconn.commit()Saves changes (for INSERT/UPDATE/DELETE)
5Closeconn.close()Frees resources. Always do this!

Study Deep: The Cursor Pattern

Think of the Connection object as the physical "pipe" leading to the database. The Cursor object is the "hand" inside that pipe.

  • Why a Cursor? Without it, you'd have to read the entire database into your computer's memory at once (slow and memory-intensive).
  • The Efficiency: The Cursor lets you pull one row at a time, or small batches, exactly when you're ready to process them. This is crucial for handling millions of records without crashing your application.
Important: Step 4 (Commit) is only needed for write operations. SELECT queries don't modify data, so no commit is needed.

3. Best Practices: Context Manager

Use Python's with statement to auto-close connections (even on error):

import sqlite3

with sqlite3.connect('my_database.db') as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")
    rows = cursor.fetchall()
# Connection auto-closes here, even if an error occurred

4. SQL Basics (Refresher)

CategoryCommandPurposeSyntax Example
DDL (Structure)CREATECreates a new tableCREATE TABLE users (id INT, name TEXT)
DDLALTERModifies table structureALTER TABLE users ADD email TEXT
DDLDROPDeletes a table entirelyDROP TABLE users
DML (Data)INSERTAdds new rowsINSERT INTO users VALUES (1, 'John')
DMLSELECTReads/queries dataSELECT * FROM users WHERE id=1
DMLUPDATEModifies existing rowsUPDATE users SET name='Jane' WHERE id=1
DMLDELETERemoves rowsDELETE FROM users WHERE id=1

DDL vs. DML:

  • DDL (Data Definition Language): Defines the structure (tables, columns). Changes are auto-committed.
  • DML (Data Manipulation Language): Manipulates the data (rows). Requires explicit commit().