Python Notes: Database Connectivity & Multithreading
Python Database Connectivity Using CRUD
What is Python Database Connectivity Using CRUD Operations
1. Introduction:
Python allows connection with databases like MySQL, SQLite, etc., to perform operations on stored data.
These operations are called CRUD:
- C - Create (Insert)
- R - Read (Select)
- U - Update
- D - Delete
2. Connecting to MySQL:
import [Link]
con = [Link](
host="localhost",
user="root",
password="yourpassword",
database="yourdbname"
cursor = [Link]()
3. CRUD Operations:
Create:
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
val = ("Amit", 21)
[Link](sql, val)
[Link]()
Python Notes: Database Connectivity & Multithreading
Read:
[Link]("SELECT * FROM students")
result = [Link]()
for row in result:
print(row)
Update:
sql = "UPDATE students SET age = %s WHERE name = %s"
val = (22, "Amit")
[Link](sql, val)
[Link]()
Delete:
sql = "DELETE FROM students WHERE name = %s"
val = ("Amit",)
[Link](sql, val)
[Link]()
Close Connection:
[Link]()
[Link]()
Key Points:
- Use cursor to run SQL queries.
- Use commit() to save changes.
- Always close the connection.
Python Notes: Database Connectivity & Multithreading
Multithreading in Python
What is Multithreading?
1. Definition:
Multithreading is a technique where multiple threads run concurrently in a program, sharing the same
memory. It helps in performing multiple tasks at once.
2. Advantages:
- Improves performance (especially for I/O tasks)
- Makes programs more responsive
- Useful for background tasks
3. Methods of Multithreading in Python:
Method 1: Using Thread class directly
import threading
def task():
print("Hello")
t = [Link](target=task)
[Link]()
[Link]()
Method 2: Subclassing Thread
class MyThread([Link]):
def run(self):
print("Thread running")
t = MyThread()
[Link]()
[Link]()
Python Notes: Database Connectivity & Multithreading
Method 3: ThreadPoolExecutor
from [Link] import ThreadPoolExecutor
def task(n):
print(f"Task {n} running")
with ThreadPoolExecutor(max_workers=3) as executor:
for i in range(5):
[Link](task, i)
4. Important Concepts:
- start(): starts thread
- join(): waits for thread to finish
- daemon: background thread
- Lock: used to handle shared data
5. Limitation:
Due to GIL, only one thread runs at a time in Python interpreter. For CPU-bound tasks, multiprocessing is
better.
Conclusion:
Multithreading is great for I/O-bound and background tasks and is implemented using the threading module
or [Link].