UNIT 5
DATABASE INTERACTION
Connecting a Python application to an SQL database involves using a Python library
like sqlite3 to establish a connection and execute SQL queries. This allows you to
interact with the database for data storage, retrieval, and manipulation.
Steps for SQL Database Connection:-
1. Choose a Library: sqlite3 for connecting to MySQL databases.
2. Import the Library: you need to import sqlite3
3. Establish the Connection Object: Use sqlite3.connect() function to the connection
to the database.
4. Create a cursor object: It is used to execute SQL queries and retrieve results.
5. Execute SQL queries: You can execute SQL queries, such as creating table, inserting
table, querying/searching data.
6. Commit transactions: You need to commit() the transaction to ensure that your
changes are saved to the database.
7. Close the connection: Use close() method on the connection object, once your
operations are complete.
Basic SQL table operations:-
1. Creating Tables: Use the CREATE TABLE statement to define new table.
2. Inserting Data: Use the INSERT INTO statement to add new records into a table.
3. Retrieving Data: Use the SELECT statement to retrieve data from a table.
4. Updating Data: Use the UPDATE statement to modify existing records in a table.
5. Deleting Data: Use the DELETE FROM statement to remove records from a table.
6. Altering Tables: Use the ALTER TABLE statement to modify the structure of an
existing table.
CREATING AND SEARCHING TABLES
In Python, creating and searching tables usually refers to manipulating data within a database,
Like MySQL.
Creating tables involves defining the structure (columns, data types, constraints) of a
table in a SQL database, Use the CREATE TABLE statement to define new table
Searching involves querying the table to retrieve data based on specific criteria. Use
the SELECT statement to retrieve data from a table
Reading and storing configuration information in a database:
Reading and storing configuration information in a database using Python, approach making
it easier to manage and update configuration value across different parts of an application or
system.
Reading configuration: it use the SELECT statement to retrieve data from a table
Storing configuration: It use the INSERT INTO statement to add new records into a
table.
Programming using Database connections
import sqlite3
# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('mydatabase.db')
# Create a cursor object
cursor = conn.cursor()
# Execute a query to create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER
)
''')
# Execute a query to insert data
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 30))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Bob', 25))
# Commit the changes
conn.commit()
# Execute a query to select data
cursor.execute("SELECT * FROM users")
# Fetch all results
rows = cursor.fetchall()
# Print the results
for row in rows:
print(row)
# Close the connection
conn.close()
Unit 5
Multithreading
A thread is a light-weight smallest part of the program that can run concurrently with other
thread of the same process.
Thread are independent
It doesn’t affect the execution of other thread.
All thread of the process share the common memory.
The process of executing multiple threads simultaneously is known as multithreading.
In simpler words, a thread is a computation process that is to be performed by a computer.
There are two ways to create a new Thread:-
1. Creating python threads using class:-
We created a sub-class of the thread class.
Then we override the __init__ function/Constructor of the thread class.
Then we override the run method to define the behaviour of the thread.
The start() method starts a Python thread.
2. Creating python threads using function:-
We defined a function to create a thread.
Then we used the threading module to create a thread that invoked the
function as its target.
Then we used start() method to start the Python thread.
Forking threads
Forking in Python, we can using os.fork() to creates a new process that is a copy of the
existing one. It does not duplicate threads. fork is a new process with parents inheritance.
The child process created by fork() only contains the thread that called fork(). Other threads
present in the parent process are not copied into the child.
System Call Used :
fork() : fork() is an operation where a new process creates a copy of itself. It is usually a
system call, implemented in the kernel.
getpid() : getpid() returns the process ID (PID) of the calling process.
Example:-
# Python code to create child process
import os
def parent_child():
n = os.fork()
# n greater than 0 means parent process
if n > 0:
print("Parent process and id is : ", os.getpid())
# n equals to 0 means child process
else:
print("Child process and id is : ", os.getpid())
# Driver code
parent_child()
Output:-
Child process and id is : 32523
Parent process and id is : 32524
Synchronization Thread:-
Thread synchronization is defined as a mechanism which ensures that two or more
concurrent threads do not simultaneously execute some particular program segment k nown
as critical section.
Where, Critical section refers to the parts of the program where the shared resource
is accessed.
Concurrent accesses to shared resource can lead to race condition.
A race condition occurs when two or more threads can access shared data and they try to
change it at the same time.
Using Locks:-
Threading module provides a Lock class to deal with the race conditions.
Lock class provides following methods:
acquire ([blocking]) : To acquire a lock. A lock can be blocking or non-blocking.
release() : To release a lock
Programming using multithreading:-
import threading
x=0
lock = threading.Lock()
def increment():
global x
lock.acquire()
x += 1
lock.release()
def task():
for _ in range(100000):
increment()
if __name__ == "__main__":
threads = []
for _ in range(2):
thread = threading.Thread(target=task)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print("Final value of x:", x)