-
[필기] DB - SQL쿼리 - ORMSQL 2021. 7. 29. 15:40
얄팍한 SQL쿼리문과 그보단 조금 나은 파이썬을 통해 DB를 생성, 관리, 데이터를 뽑아오는 법을 배우는 중이다.
귀도 아저씨의 PEP249 설명 - PEP249 Documentation:
https://www.python.org/dev/peps/pep-0249/
sqlite3 or psycopg2
DB와 python을 연결해주는 패키지. SQL쿼리문 사용.
SQLAlchemy: ORM
DB와 프로그래밍언어를 연결해주는 중간다리. SQL쿼리문없이 프로그래밍언어 사용.
1. sqlite3 - > sqlite 연결 등
documentation: https://docs.python.org/ko/3/library/sqlite3.html
sqlite3 — SQLite 데이터베이스용 DB-API 2.0 인터페이스 — Python 3.9.6 문서
바로 가기 메서드 사용하기 Connection 객체의 비표준 execute(), executemany() 및 executescript() 메서드를 사용하면, (종종 불필요한) Cursor 객체를 명시적으로 만들 필요가 없으므로, 코드를 더 간결하게 작
docs.python.org
코드예시:
import sqlite3 conn = sqlite3.connect('db_name.db') cur = conn.cursor() cur.execute("""CREATE TABLE test_table ( name VARCHAR(32), age INT); """) cur.fetchall() conn.commit() conn.close()
2. psycopg2 -> postgresql 연결
설치:
pip install psycopg2
tutorial: https://wiki.postgresql.org/wiki/Psycopg2_Tutorial
Psycopg2 Tutorial - PostgreSQL wiki
Access PostgreSQL with Python There are any number of programming languages available for you to use with PostgreSQL. One could argue that PostgreSQL as an Open Source database has one of the largest libraries of Application Programmable Interfaces (API) a
wiki.postgresql.org
코드예시:
import psycopg2 conn = psycopg2.connect( host="서버 호스트 주소", database="데이터베이스 이름", user="유저 이름", password="유저 비밀번호")
3. SQLAlchemy
tutorial documentation : https://docs.sqlalchemy.org/en/14/orm/tutorial.html
Object Relational Tutorial (1.x API) — SQLAlchemy 1.4 Documentation
A Query object is created using the query() method on Session. This function takes a variable number of arguments, which can be any combination of classes and class-instrumented descriptors. Below, we indicate a Query which loads User instances. When evalu
docs.sqlalchemy.org
설치:
pip install sqlalchemy
엔진 - 데이터 베이스를 연결해주기 위함
from sqlalchemy import create_engine engine = create_engine("데이터베이스 주소") #e.g. engine = create_engine("sqlite:///test.db") - 어떤 데이터 베이스인지 명시 + "://" + / 는 상대경로 //는 절대경로
베이스 - 매핑을 하기 위함 (Table과 Class)
실제 DB에 있던 테이블과 "매핑" 및 신규 테이블(클래스로 생성)을 "생성"해준다.
from sqlalchemy.orm import declarative_base Base = declarative_base()
예시:
test.py 파이썬 파일 하기와 같이 작성 후 실행시
from sqlalchemy import Column, Integer, String class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) def __repr__(self): return f"User {self.id}: {self.name}" class Products(Base): __tablename__ = 'products' id = Column(Integer, primary_key=True) name = Column(String) origin = Column(String(10)) def __repr__(self): return f"Prod. {self.id}: {self.name}" Base.metadata.create_all(engine)
테이블이 생성된다.
(실제로 USER테이블은 미리 만들어두고, PRODUCT는 만들지 않은 sqlite3파일에,
데이터 로우도 추가해준 다음에 파이썬 파일 실행하였는데,
기존 user 테이블 및 데이터는 그대로,
products는 새로 생성되었다.)
def __repr__(self): 설정과 미설정시 차이
클래스 인스턴스 출력시에 하기와 같이 출력된다.
첫번째는
def __repr__(self):
return f"User {self.id}: {self.name}"두번째값은
따로 설정 하지 않았을때다.
테이블 생성 및 스키마 생성이 완료되면, 꼭 하기 선언을 통해 테이블 생성과 관계 형성을 진행해주어야한다.
Base.metadata.create_all(engine) #드랍시에는 Base.metadata.drop_all(engine)
세션메이커 생성:
from sqlalchemy.orm import Session session = Session(bind=engine) #이렇게 바로 engine을 설정해줘도 되고, session.configure(bind=engine) #나중에 configure속성으로 선언해주어도 된다.
'SQL' 카테고리의 다른 글
[HackerRank] Top Competitors (0) 2021.09.28 [HackerRank] Binary Tree Nodes (0) 2021.09.23 [HackerRank] Weather Observation Station 5 (0) 2021.09.23 [sqlalchemy] 테이블간 relationship 설정 (0) 2021.07.26 [MySQL-일기장] COUNT(*) 는 NULL을 포함한다 (0) 2021.07.22