Databases and Data Storage in python

Databases and Data Storage in Python

Python offers powerful tools for working with databases and data storage. Whether you're working with relational databases, NoSQL databases, or simple file-based storage, Python provides easy-to-use libraries and modules.


πŸ“¦ 1. File-Based Data Storage

a. Text Files (CSV, TXT)

Modules: csv, open()


Use Case: Lightweight storage, data exchange between systems


python

Copy

Edit

import csv


# Writing to CSV

with open('data.csv', 'w', newline='') as file:

    writer = csv.writer(file)

    writer.writerow(["Name", "Age"])

    writer.writerow(["Alice", 25])


# Reading from CSV

with open('data.csv', 'r') as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

b. JSON Files

Modules: json


Use Case: Store structured data, APIs, configuration files


python

Copy

Edit

import json


data = {"name": "Alice", "age": 25}


# Write to JSON file

with open("data.json", "w") as f:

    json.dump(data, f)


# Read from JSON file

with open("data.json", "r") as f:

    result = json.load(f)

    print(result)

πŸ—ƒ️ 2. Relational Databases (SQL)

a. SQLite

Module: sqlite3 (built-in)


Use Case: Lightweight embedded database


python

Copy

Edit

import sqlite3


conn = sqlite3.connect('example.db')

cursor = conn.cursor()


cursor.execute('''CREATE TABLE IF NOT EXISTS users (name TEXT, age INTEGER)''')

cursor.execute('''INSERT INTO users (name, age) VALUES (?, ?)''', ("Alice", 25))


conn.commit()


cursor.execute('SELECT * FROM users')

print(cursor.fetchall())


conn.close()

b. MySQL / PostgreSQL

Libraries: mysql-connector-python, psycopg2, or ORM like SQLAlchemy


bash

Copy

Edit

pip install mysql-connector-python psycopg2-binary SQLAlchemy

🌐 3. NoSQL Databases

a. MongoDB

Library: pymongo


Use Case: Document-based storage (flexible schema)


bash

Copy

Edit

pip install pymongo

python

Copy

Edit

from pymongo import MongoClient


client = MongoClient("mongodb://localhost:27017/")

db = client["mydatabase"]

collection = db["users"]


collection.insert_one({"name": "Alice", "age": 25})


for user in collection.find():

    print(user)

⚙️ 4. Object-Relational Mapping (ORM)

a. SQLAlchemy

Allows you to interact with databases using Python classes and objects.


python

Copy

Edit

from sqlalchemy import create_engine, Column, Integer, String

from sqlalchemy.orm import declarative_base, sessionmaker


engine = create_engine("sqlite:///example.db")

Base = declarative_base()


class User(Base):

    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)

    name = Column(String)

    age = Column(Integer)


Base.metadata.create_all(engine)


Session = sessionmaker(bind=engine)

session = Session()


user = User(name="Bob", age=30)

session.add(user)

session.commit()

Summary Table

Storage Type Tools / Libraries Best For

Text/CSV/JSON open, csv, json Simple data formats, configs

SQLite sqlite3 Lightweight local database

MySQL/PostgreSQL mysql-connector, psycopg2, SQLAlchemy Full-scale relational databases

MongoDB pymongo Schema-less, flexible data

ORM SQLAlchemy, Django ORM Pythonic database interaction

Learn Full Stack Python Course in Hyderabad

Read More

Building Secure Backend APIs in Python

Setting Up RESTful APIs with Flask or Django

Visit Our IHUB Talent Training Institute in Hyderabad

Get Directions



Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing

A Beginner's Guide to ETL Testing: What You Need to Know