Sunday, March 10, 2024

What is Psycopg, sqlalchemy

Psycopg2 is a popular Python library that acts as a PostgreSQL database adapter. It implements the Python Database API Specification v2.0, allowing you to interact with PostgreSQL databases from Python applications using a consistent and standardized interface.

Here's a quick summary of Psycopg2 usage:

1. Installation:

Use pip to install Psycopg2:

Bash

pip install psycopg2

Python

import psycopg2


# Connect to the database

conn = psycopg2.connect(dbname="your_database", user="your_user", password="your_password", host="your_host")


# Create a cursor object

cur = conn.cursor()


# Execute a query

cur.execute("SELECT * FROM your_table")


# Fetch results (can be one row at a time or all at once)

rows = cur.fetchone()  # One row

# or

rows = cur.fetchall()  # All rows


# Print results

for row in rows:

    print(row)


# Close the cursor and connection

cur.close()

conn.close()




SQLAlchemy is a powerful Python library known as an Object Relational Mapper (ORM). It acts as a bridge between Python objects and relational databases, simplifying how you interact with databases in your Python applications. Here's a summary of SQLAlchemy and its usage:


Summary:


ORM Approach: SQLAlchemy uses an Object Relational Mapping approach, allowing you to define Python classes that map to database tables. This makes your code more readable and maintainable as you work with objects instead of raw SQL queries.

Flexibility: It offers flexibility. You can use the ORM for rapid development or switch to writing raw SQL queries when needed for complex operations.

Database Agnostic: SQLAlchemy is database-agnostic. It supports various relational databases (like PostgreSQL, MySQL, SQLite) through dialects, allowing you to use the same core concepts across different database systems.

Basic Usage:


Here's a simplified example of using SQLAlchemy:


Import and Define Engine:

Python

from sqlalchemy import create_engine


# Connect to the database (replace placeholders)

engine = create_engine('postgresql://user:password@host/database')



Python

from sqlalchemy import Column, Integer, String

from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()  # Base class for models


class User(Base):

    __tablename__ = 'users'  # Table name


    id = Column(Integer, primary_key=True)

    name = Column(String)

    email = Column(String)


No comments:

Post a Comment