psycopg2 라이브러리 설치
pip install psycopg2
Connection 생성
import psycopg2
# database connection 생성
db = psycopg2.connect(host='localhost', dbname='postgres',user='postgres',password='910506',port=5432)
# 커서 생성
cursor=db.cursor()
SQL 쿼리를 통한 CRUD
# CREATE TABLE
create_query = "CREATE TABLE first (id INT PRIMARY KEY, name VARCHAR(32), year INT, gender VARCHAR(32), count INT);"
# INSERT DATA
insert_query = "INSERT INTO first VALUES(0, 'Tom', 2023, 'M', 1100);"
# UPDATA DATA
update_query = """
UPDATE first
SET id = 1,
name = 'HYUNSOO',
year = '1991',
gender = 'M',
count = '1000'
WHERE id = 1;
"""
# DELETE DATA
delete_query = "DELETE FROM first WHERE id = 1;"
# SQL 쿼리 실행
cursor.execute(create_query)
# COMMIT을 통한 변경 내용 확정
db.commit()
Python 객체와 관계형 DB의 data를 매핑해주는 것
장점
단점
sqlalchemy 라이브러리 설치
pip install sqlalchemy
Connection 생성
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine_name = 'postgresql'
user_id = 'postgres'
user_pw = '910506'
host = 'localhost'
ip = '5432'
db_name = 'postgres'
db = create_engine(f'{engine_name}://{user_id}:{user_pw}@{host}:{ip}/{db}')
Session = sessionmaker(db)
session = Session()
본격 ORM 실행
Database 내의 Table을 Python Class와 매핑해준다.
from sqlalchemy import declarative_base, Column, INTEGER, VARCHAR
Base = declarative_base()
class First(Base):
__tablename__ = 'first'
id = Column('id', INTEGER, primary_key=True)
name = Column('name', VARCHAR(10), nullable=False)
year = Column('year', INTEGER, nullable=False)
gender = Column('gender', VARCHAR(10), nullable=False)
count = Column('count', INTEGER, nullable=False)
# Create
Base.metadata.create_all(db)
# Drop
First.__table__.drop(db)
sqlalchemy 메서드를 이용한 CRUD
# 1) SELECT ALL
res = session.query(First).all()
for i in res:
print(i.id, i.name, i.year, i.gender, i.count)
# 2) INSERT
data1 = First(name='hyunsoo', year=1990, gender='M', count=1234)
session.add(data1)
# 3) UPDATE
session.query(First).filter(First.name == 'hyunsoo').update({'name':'hyunsoo', 'gender':'F'})
# 4) DELETE
session.query(First).filter(First.name == 'hyunsoo').delete()
# 결과 저장
session.commit()
Connection 생성
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import sessionmaker, declarative_base
db = create_engine('postgresql://[USER ID]:[USER PW]@[IP]:[PORT]/[DB NAME]')
# 세션 :
Session = sessionmaker(db)
session = Session()
meta = MetaData()
테이블 선언
# 테이블 스키마에 맞게 Column 생성 후 테이블 선언
core_table = Table(
'first', meta,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('name', String),
Column('year', Integer),
Column('gender', String),
Column('count', Integer)
)
meta.create_all(db)
sqlalchemy core 메서드를 이용한 CRUD
SELECT ALL
res = core_table.select()
result = session.execute(res)
for row in result:
print(row)
INSERT
from sqlalchemy import insert
# INSERT 1건
stmt = insert(core_table).values(name="hahaha", year=2023, gender="M", count=654)
with db.connect() as conn:
result = conn.execute(stmt)
conn.commit()
-----------------------------------------------------------------------------
# INSERT 다수
stmt = insert(core_table)
data_list = [
{"name": "tom", "year": 2023, "gender": "M", "count": 12},
{"name": "ann", "year": 2000, "gender": "F", "count": 32}
]
with db.connect() as conn:
result = conn.execute(stmt, data_list)
conn.commit()
UPDATE
from sqlalchemy import update
stmt = update(core_table).where(core_table.c.name == 'ann').values(year=1990)
with db.connect() as conn:
result = conn.execute(stmt)
conn.commit()
DELETE
from sqlalchemy import update
stmt = delete(core_table).where(core_table.c.name == 'ann')
with db.connect() as conn:
result = conn.execute(stmt)
conn.commit()
Core
DBAPI (Python Database API Specification)
ORM