MCA – I year
SEMESTER - II
Course Code MCA 221
Course Title: Python Programming
By:-
Vinita Thanvi
Assistant Professor
Lucky Institute of Professional Studies
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Database Interaction:
• SQL Database connection using Python,
• creating and searching tables,
• reading and storing configuration information on database,
• programming using database connections.
Python Multithreading:
• Understanding threads,
• forking threads,
• synchronizing the threads, programming using multithreading.
By:- Vinita Thanvi, Assistant Professor, LIPS
Index
[Link] Objectives
[Link] Interaction in Python
[Link] Connection using Python
[Link] Creation & Searching
[Link] Storage
[Link] with Database
[Link] Concepts
[Link] Creation & Synchronization
[Link] Studies
[Link]
[Link] (Quiz)
[Link]
[Link] Year Questions (BTU)
[Link] & Discussion
By:- Vinita Thanvi, Assistant Professor, LIPS
Learning Objectives
Students will be able to:
•Connect Python with SQL database
•Perform CRUD operations
•Implement multithreading
•Synchronize threads effectively
By:- Vinita Thanvi, Assistant Professor, LIPS
DATABASE INTERACTION
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
How to Connect Python with SQL Database?
• Python is a high-level, general-purpose, and very popular programming language.
• Basically, it was designed with an emphasis on code readability, and programmers can
express their concepts in fewer lines of code.
• We can also use Python with SQL using the ‘MySQL Connector Python module.
• The diagram given below illustrates how a connection request is sent to MySQL connector
Python, how it gets accepted from the database and how the cursor is executed with result
data.
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Creating a table in MySQL
• The CREATE TABLE statement is used to create tables in MYSQL database.
• Here, we need to specify the name of the table and, definition (name and
datatype) of each column.
Syntax
Following query creates a table named EMPLOYEE in MySQL with five columns
namely, FIRST_NAME, LAST_NAME, AGE, SEX and, INCOME.
mysql> CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
);
By:- Vinita Thanvi, Assistant Professor, LIPS
Creating a table in MySQL using python
The method named execute() (invoked on the cursor object) accepts two variables −
A String value representing the query to be executed.
An optional args parameter which can be a tuple or, list or, dictionary, representing
the parameters of the query (values of the place holders).
It returns an integer value representing the number of rows effected by the query.
Once a database connection is established, you can create tables by passing the
CREATE TABLE query to the execute() method
By:- Vinita Thanvi, Assistant Professor, LIPS
In short, to create a table using python:
• Import [Link] package.
• Create a connection object using the [Link]() method, by passing the
user name, password, host (optional default: localhost) and, database (optional) as
parameters to it.
• Create a cursor object by invoking the cursor() method on the connection object created
above.
• Then, execute the CREATE TABLE statement by passing it as a parameter to the execute()
method.
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Database Connection (Python + SQLite)
Syntax:
import sqlite3
conn = [Link]("[Link]")
cursor = [Link]()
print("Connected Successfully")
Output:
Connected Successfully
By:- Vinita Thanvi, Assistant Professor, LIPS
Creating Table
[Link]("""
CREATE TABLE student(
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
""")
[Link]()
Output:
Table Created Successfully
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Output:
CCECC
Connection → Cursor → Execute → Commit → Close
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Insert & Search Data
[Link]("INSERT INTO student VALUES(1,'Amit',85)")
[Link]()
[Link]("SELECT * FROM student")
rows = [Link]()
for row in rows:
print(row)
Output:
(1, 'Amit', 85)
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Reading .ini Configuration Files
• The configparser module can be used to read configuration files.
[Link]("""
CREATE TABLE config(
key TEXT,
value TEXT
)
""")
[Link]("INSERT INTO config VALUES('theme','dark')")
[Link]()
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
•config table stores application settings
•Example:
•theme → dark/light mode
•language → English/Hindi
If You Run Again (Duplicate Issue)
Use:
INSERT OR IGNORE INTO config VALUES('theme','dark')
Used to store:
•Settings
•Preferences
By:- Vinita Thanvi, Assistant Professor, LIPS
Database Programming Concepts
•Connection object
•Cursor object
•Execute queries
•Commit changes
•Close connection
By:- Vinita Thanvi, Assistant Professor, LIPS
MULTITHREADING
By:- Vinita Thanvi, Assistant Professor, LIPS
An Intro to Threading in Python
• A thread is an entity within a process that can be scheduled for execution.
• Also, it is the smallest unit of processing that can be performed in an OS
(Operating System).
• In simple words, a thread is a sequence of such instructions within a program
that can be executed independently of other code.
• For simplicity, you can assume that a thread is simply a subset of a process!
• A thread contains all this information in a Thread Control Block (TCB):
By:- Vinita Thanvi, Assistant Professor, LIPS
Thread Identifier: Unique id (TID) is assigned to every new thread
Stack pointer: Points to the thread’s stack in the process. The stack contains the local
variables under the thread’s scope.
Program counter: a register that stores the address of the instruction currently being
executed by a thread.
Thread state: can be running, ready, waiting, starting, or done.
Thread’s register set: registers assigned to thread for computations.
Parent process Pointer: A pointer to the Process control block (PCB) of the process that the
thread lives on.
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Multiple threads can exist within one process where:
Each thread contains its own register set and local variables (stored in the stack).
All threads of a process share global variables (stored in heap) and the program code.
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
• Multithreading is defined as the ability of a processor to execute multiple
threads concurrently.
• In a simple, single-core CPU, it is achieved using frequent switching between
threads.
• This is termed context switching.
• In context switching, the state of a thread is saved and the state of another
thread is loaded whenever any interrupt (due to I/O or manually set) takes
place.
• Context switching takes place so frequently that all the threads appear to be
running parallelly (this is termed multitasking).
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Multithreading programming in Python
In Python, the threading module provides a very simple and intuitive API
for spawning multiple threads in a program. Let us try to understand
multithreading code step-by-step.
Step 1: Import Module
First, import the threading module.
import threading
Step 2: Create a Thread
To create a new thread, we create an object of the Thread class. It takes the
‘target’ and ‘args’ as the parameters. The target is the function to be
executed by the thread whereas the args is the arguments to be passed to the
target function.
t1 = [Link](target, args)
t2 = [Link](target, args)
By:- Vinita Thanvi, Assistant Professor, LIPS
Step 3: Start a Thread
To start a thread, we use the start() method of the Thread class.
[Link]()
[Link]()
Step 4: End the thread Execution
Once the threads start, the current program (you can think of it like a main thread) also
keeps on executing. In order to stop the execution of the current program until a thread is
complete, we use the join() method.
[Link]()
[Link]()
As a result, the current program will first wait for the completion of t1 and then t2. Once,
they are finished, the remaining statements of the current program are executed.
By:- Vinita Thanvi, Assistant Professor, LIPS
# function to print square of given num
print("Square: {}" .format(num * num))
if __name__ =="__main__":
# creating thread
t1 = [Link](target=print_square, args=(10,))
t2 = [Link](target=print_cube, args=(10,))
# starting thread 1
[Link]()
# starting thread 2
[Link]()
# wait until thread 1 is completely executed
[Link]()
Output:
# wait until thread 2 is completely executed Square: 100
Cube: 1000
[Link]()
Done!
# both threads completely executed
print("Done!")
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Synchronizing Threads in Python
• The threading module provided with Python includes a simple-to-implement locking mechanism that
allows you to synchronize threads.
• A new lock is created by calling the Lock() method, which returns the new lock.
• The acquire(blocking) method of the new lock object is used to force threads to run synchronously.
• The optional blocking parameter enables you to control whether the thread waits to acquire the lock.
• If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and
with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be
released.
• The release() method of the new lock object is used to release the lock when it is no longer required.
By:- Vinita Thanvi, Assistant Professor, LIPS
Thread Synchronization
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Why Synchronization?
•Prevent data inconsistency
•Avoid race conditions
•Ensure safe execution
By:- Vinita Thanvi, Assistant Professor, LIPS
Case Study – Banking System
Database:
•Store account details
Threads:
•Handle multiple transactions
👉 Benefit:
•Faster processing
•Concurrent users
By:- Vinita Thanvi, Assistant Professor, LIPS
Case Study – Online Result System
•DB stores marks
•Threads generate results simultaneously
By:- Vinita Thanvi, Assistant Professor, LIPS
Forking Threads
• Forking Threads means creating multiple threads from a main thread (parent
thread) so that tasks can run concurrently (at the same time).
• It is also called spawning or creating threads.
Concept
A main thread starts execution
It creates (forks) child threads
Each thread performs its own task independently
Key Points
Threads share the same memory
Execution happens in parallel
Improves performance
Useful for multitasking
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
import threading
def task():
print("Child Thread Running")
# Main thread creates (forks) a new thread
t = [Link](target=task)
[Link]() # fork/start thread
[Link]()
print("Main Thread Ended")
Output
Child Thread Running
Main Thread Ended
By:- Vinita Thanvi, Assistant Professor, LIPS
Summary
•Python connects with SQL using sqlite3
•CRUD operations are essential
•Threads improve performance
•Synchronization ensures safety
By:- Vinita Thanvi, Assistant Professor, LIPS
Assessment (Quiz)
[Link] is sqlite3?
[Link] is a thread?
[Link] between process and thread
[Link] is lock in threading?
[Link] is cursor object?
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Assignments
[Link] student database and perform CRUD
[Link] program using 2 threads
[Link] thread synchronization
[Link] configuration in DB
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS
Previous Year Questions (BTU Pattern)
🔹 Short Questions
•Define thread
•What is sqlite3?
•What is cursor?
🔹 Medium Questions (5 Marks)
Explain database connection in Python
Write program to create table
Explain multithreading
Long Questions (10 Marks)
Write a Python program to:
Connect database
Create table
Insert and display records
Explain multithreading with example
Write program using thread synchronization
By:- Vinita Thanvi, Assistant Professor, LIPS
Questions & Discussion
•Why use multithreading?
•What is DB connection lifecycle?
•What problems occur without synchronization?
By:- Vinita Thanvi, Assistant Professor, LIPS
By:- Vinita Thanvi, Assistant Professor, LIPS