Unit-3: Python interaction with SQLite:
Python interaction with SQLite:
- 3.1 Module: Concepts of module and Using modules in
- python.3.1.1 Setting PYTHONPATH, Concepts of Namespace and Scope
- 3.1.2 Concepts of Packages in python
- 3.2 Importing sqlite3 module
- 3.2.1 connect () and execute() methods.
- 3.2.2 Single row and multi-row fetch ( fetchone(), fetchall())
- 3.2.3 Select, Insert, update, delete using execute () method.
- 3.2.4 commit () method.
NOTES
β What is a Module in Python?
A module in Python is simply a file containing Python code β it could include functions, variables, and classes. Modules help in organizing code logically and reusing it across different programs.
File extension of a module:
.pyYou can create your own module or use Python’s built-in modules.
π Benefits of Using Modules:
Avoids repetition of code.
Makes code more organized and manageable.
Promotes code reuse.
Helps in debugging by isolating functionality
β Types of Modules
| Type | Description |
|---|---|
| Built-in Modules | Already available in Python, like math, random, sqlite3 |
| User-defined Modules | Created by the user to suit specific project needs |
| External Modules | Provided by third parties (like pandas, numpy), and need to be installed using pip |
β Importing Modules
There are several ways to import a module:
import math
print(math.sqrt(16)) # Output: 4.0
from math import sqrt
print(sqrt(25)) # Output: 5.0
import sqlite3 as db
conn = db.connect(‘test.db’) # SQLite module with alias
β Using Modules in Python (SQLite Example)
Python provides a built-in module called sqlite3 that allows interaction with SQLite databases. This module lets you create, read, update, and delete (CRUD) data from a database file.
πΉ Steps to Use sqlite3 Module:
import sqlite3 # Step 1: Import the module
# Step 2: Connect to a database (or create if it doesnβt exist)
conn = sqlite3.connect(‘student.db’)
# Step 3: Create a cursor object
cur = conn.cursor()
# Step 4: Write and execute SQL commands
cur.execute(”’
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
”’)
# Step 5: Insert data
cur.execute(“INSERT INTO students (name, marks) VALUES (?, ?)”, (‘Alice’, 90))
# Step 6: Save changes
conn.commit()
# Step 7: Retrieve data
cur.execute(“SELECT * FROM students”)
rows = cur.fetchall()
for row in rows:
print(row)
# Step 8: Close the connection
conn.close()
β Key Functions in sqlite3 Module
| Function | Purpose |
|---|---|
connect() |
Connects to the database |
cursor() |
Creates a cursor for executing SQL |
execute() |
Executes an SQL command |
commit() |
Saves changes to the database |
fetchall() |
Retrieves all records from a query |
close() |
Closes the connection to the database |
β 3.1.1 Setting PYTHONPATH, Concepts of Namespace and Scope
β
What is PYTHONPATH?
PYTHONPATH is an environment variable used by Python to locate the directories where your Python modules and packages are stored. When you import a module, Python searches in:
The current working directory,
Standard library folders,
Paths listed in
PYTHONPATH.
β
Why Set PYTHONPATH?
To import user-defined modules stored in different directories.
To customize your development environment.
Useful in large projects where modules are spread across multiple folders.
β
How to Set PYTHONPATH:
βΎ On Windows:
To make it permanent, add the line to your ~/.bashrc or ~/.bash_profile.
β Example Use:
Suppose you have this structure:
If you’re running main.py but want to import utils, you can set:
πΉ 2. Concept of Namespace in Python
β What is a Namespace?
A namespace is like a naming system that ensures names are unique and can be used without conflicts. It acts like a container that holds names (variables, functions, objects) and their references.
β Types of Namespaces:
| Namespace Type | Description |
|---|---|
| Built-in | Automatically created when Python starts (e.g., print(), len()). |
| Global | For variables defined at the top level of a script or module. |
| Local | For variables defined inside functions or methods. |
| Enclosing | Refers to the namespaces of enclosing functions in case of nested functions. |
x = 10 # Global namespace
def func():
y = 5 # Local namespace
print(x) # Accesses global x
func()
πΉ 3. Concept of Scope in Python
β What is Scope?
Scope defines the visibility and lifetime of a variable. In simple words, it determines where in your code a variable is accessible.
β Scope Levels (LEGB Rule):
β Example of Scope:
| Scope | Description |
|---|---|
| L β Local | Names inside the current function. |
| E β Enclosing | Names in enclosing functions (for nested functions). |
| G β Global | Names in the top-level script/module. |
| B β Built-in | Predefined names in Python (like str, int). |
x = 100 # Global
def outer():
y = 50 # Enclosing
def inner():
z = 10 # Local
print(x, y, z)
inner()
outer()
β 3.1.2 Concepts of Packages in Python
πΉ What is a Package in Python?
A package in Python is a way of organizing related modules into a single directory. It is essentially a folder containing multiple Python files (modules) and a special __init__.py file that marks the directory as a package.
Packages are used to:
Group related code together
Make large projects modular
Enable code reuse and easy maintenance
β Difference Between Module and Package
| Feature | Module | Package |
|---|---|---|
| Meaning | A single .py file |
A directory with modules and __init__.py |
| Usage | Used to reuse code | Used to organize and structure large applications |
| Example | math, os |
numpy, pandas |
__init__.py: Initializes the package. It can be empty or contain initialization code.module1.pyandmodule2.py: Regular Python files containing functions, classes, or variables.sub_package: A package inside a package (nested package).
πΉ Creating a Simple Package
Suppose you want to create a package called math_utils with basic math operations.
Step 1: Create Folder and Files
Step 2: Define Functions in Modules
addition.py
β Built-in & External Python Packages
Built-in packages: Python includes many built-in packages like
email,http, andxml.External packages: Packages like
numpy,pandas, andflaskare developed by the community and installed using pip:
πΉ Advantages of Using Packages
Keeps project code well-organized and modular
Easier to manage large applications
Avoids name clashes between modules
Encourages reusable code
β 3.2 Python Interaction with SQLite β sqlite3 Module
πΉ 3.2. Importing sqlite3 Module
Python provides a built-in module called sqlite3 to work with SQLite databases. This module allows you to create, read, update, and delete data stored in .db files using SQL commands.
β Importing the Module:
This gives you access to all the SQLite functionalities like connecting to a database, executing SQL queries, and handling results.
πΉ 3.2.1 connect() and execute() Methods
β
connect() Method:
Used to establish a connection to an SQLite database.
If
student.dbdoes not exist, it will be created.Returns a connection object.
β
execute() Method:
Used to run SQL commands like CREATE, INSERT, SELECT, UPDATE, DELETE, etc.
πΉ 3.2.2 Single Row and Multi-Row Fetch
Once a SELECT query is executed, you can retrieve data using:
β
fetchone():
Retrieves only the first row of the result set.
β
fetchall():
Retrieves all the rows returned by the query as a list of tuples.
πΉ 3.2.3 Using execute() for SELECT, INSERT, UPDATE, DELETE
β 1. INSERT data:
β 2. SELECT data:
β 3. UPDATE data:
β 4. DELETE data:
πΉ 3.2.4 commit() Method
After performing INSERT, UPDATE, or DELETE operations, the changes are not saved until you commit them.
β
Why commit() is needed:
It confirms changes made to the database.
If not called, changes may be lost after closing the connection.
β Syntax:
