Category: python
SQLite with Python
Published on 14 Aug 2026
Explanation
SQLite is a lightweight relational database that is built into Python through the sqlite3 module. It does not require a separate database server, making it useful for learning, prototypes, desktop applications, and small projects. Python can use SQLite to create databases and tables and perform CRUD operations such as INSERT, SELECT, UPDATE, and DELETE. The sqlite3.connect() function creates a connection to a database file, while cursor() is used to execute SQL statements.
Code:
import sqlite3
connection = sqlite3.connect('students.db')
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
''')
cursor.execute(
'INSERT INTO students (name, marks) VALUES (?, ?)',
('John', 85)
)
connection.commit()
cursor.execute('SELECT * FROM students')
for student in cursor.fetchall():
print(student)
connection.close()
Explanation
PostgreSQL is a powerful open-source relational database commonly used in production applications. Python applications can connect to PostgreSQL using libraries such as psycopg. After establishing a connection, a cursor can execute SQL queries to insert, retrieve, update, and delete records. Parameterized queries should always be used when working with user-provided values because they help prevent SQL injection attacks. PostgreSQL is widely used with Python backend frameworks such as FastAPI, Flask, and Django.
Code:
import psycopg
connection = psycopg.connect(
host='localhost',
database='company',
user='postgres',
password='password'
)
cursor = connection.cursor()
cursor.execute(
'SELECT id, name, salary FROM employees'
)
employees = cursor.fetchall()
for employee in employees:
print(employee)
cursor.close()
connection.close()
Explanation
A virtual environment provides an isolated Python environment for a project. It allows each project to have its own dependencies and prevents conflicts between different versions of packages. Python provides the built-in venv module to create virtual environments. A well-organized project separates application code, utilities, configuration, tests, and dependencies. The requirements.txt file can be used to store project dependencies so that the same environment can be recreated on another computer.
Code:
# Create virtual environment python -m venv venv # Activate on Windows venv\\Scripts\\activate # Activate on macOS/Linux source venv/bin/activate # Install a package pip install requests # Save dependencies pip freeze > requirements.txt # Project structure # myproject/ # ├── venv/ # ├── app/ # │ ├── __init__.py # │ ├── main.py # │ └── utils.py # ├── tests/ # ├── requirements.txt # └── README.md
Explanation
Logging is used to record events that happen while a Python application is running. Instead of using print() statements throughout an application, developers can use Python's built-in logging module. Logging provides different levels such as DEBUG, INFO, WARNING, ERROR, and CRITICAL. Logs are useful for debugging applications, tracking errors, monitoring production systems, and understanding application behavior. Logs can also be written to files instead of being displayed only on the console.
Code:
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.debug('Debug message')
logging.info('Application started')
logging.warning('This is a warning')
try:
result = 10 / 0
except ZeroDivisionError:
logging.error('Cannot divide by zero')
logging.info('Application completed')
Explanation
Unit testing is the process of testing individual units of application code, such as functions or methods. Python provides the built-in unittest framework for creating and running automated tests. Test cases can verify whether functions return expected results and whether errors are handled correctly. Common assertions include assertEqual(), assertNotEqual(), assertTrue(), assertFalse(), and assertIsNone(). Unit testing helps developers detect bugs early and makes applications safer to modify and maintain.
Code:
import unittest
def add(a, b):
return a + b
def multiply(a, b):
return a * b
class TestCalculator(unittest.TestCase):
def test_add(self):
self.assertEqual(add(10, 20), 30)
def test_multiply(self):
self.assertEqual(multiply(5, 4), 20)
def test_add_negative(self):
self.assertEqual(add(-5, 10), 5)
if __name__ == '__main__':
unittest.main()
Explanation
An Employee Management System is a practical project that combines multiple Python concepts with MySQL database connectivity. The application can perform CRUD operations such as adding employees, viewing employees, updating employee details, and deleting employees. This project can be structured using functions or classes and can later be enhanced with exception handling, logging, validation, and unit testing. Parameterized SQL queries should be used when inserting or updating data to prevent SQL injection.
Code:
import mysql.connector
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='company'
)
cursor = connection.cursor()
def add_employee(name, salary):
query = '''
INSERT INTO employees (name, salary)
VALUES (%s, %s)
'''
cursor.execute(query, (name, salary))
connection.commit()
print('Employee added successfully')
def get_employees():
cursor.execute('SELECT id, name, salary FROM employees')
for employee in cursor.fetchall():
print(employee)
add_employee('John', 50000)
get_employees()
cursor.close()
connection.close()