반응형

sqlalchemy는 파이썬에서 DB에 접근하기 위한 ORM 라이브러리다.

 

ORM은 Object Relational Mapping의 약어로써 객체(Object)와 관계형 DB(Relational)을 연결(Mapping) 해주는 것을 의미한다.

객체지향언어에서 객체(클래스)에 DB 테이블을 매핑시켜 사용한다고 생각하면 이해가 쉽다.

ORM은 설계에 따라 사용이 용이할 수도 어려워질 수가 있다.

 

* sqlalchemy

사이트 : https://www.sqlalchemy.org/

 

SQLAlchemy - The Database Toolkit for Python

The Python SQL Toolkit and Object Relational Mapper SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It provides a full suite of well known enterprise-level persisten

www.sqlalchemy.org

지원하는 Databases : SQLite, Postresql, MySQL, Oracle, MS-SQL, Firebird, Sybase 등..

사용가능한 Python 버전 : 2.5이후 또는 3.x 버전

 

SQLAlchemy를 사용하기 위해 우선적으로 DB Engine을 생성해야 한다

from sqlalchemy import create_engine
#engine 생성
#password 특수문자 포함 시 password에 url 인코딩 필요
engine = create_engine("postgresql://{username}{password}@{host}/{database}")

#password 인코딩 예시
import urllib.parse
print(urllib.parse.quote_plus("kx@jj5/g")) #'kx%40jj5%2Fg' 출력

from sqlalchemy import URL
#URL을 이용한 engine생성
#password에 특수문자가 포함 시 인코딩 하지 않고 사용할 수 있음.
url_object = URL.create(
	drivername="",
    username={username},
    password={password},
    host={host},
    database={database},
    query={"charset":"cp949"}
    )
engine = create_engine(url_object)

위와 같이 생성한다.

 

* 각 DB별 engine 생성 샘플

# mysql default
engine = create_engine("mysql://scott:tiger@localhost/foo")

# mysqlclient (a maintained fork of MySQL-Python)
engine = create_engine("mysql+mysqldb://scott:tiger@localhost/foo")

# PyMySQL
engine = create_engine("mysql+pymysql://scott:tiger@localhost/foo")

#Oracle
engine = create_engine("oracle://scott:tiger@127.0.0.1:1521/sidname")
engine = create_engine("oracle+cx_oracle://scott:tiger@tnsname")

# mssql pyodbc
engine = create_engine("mssql+pyodbc://scott:tiger@mydsn")

# pymssql
engine = create_engine("mssql+pymssql://scott:tiger@hostname:port/dbname")

# sqlite://<nohostname>/<path>
# where <path> is relative:
engine = create_engine("sqlite:///foo.db")

# Unix/Mac - 4 initial slashes in total
engine = create_engine("sqlite:////absolute/path/to/foo.db")

# Windows
engine = create_engine("sqlite:///C:\\path\\to\\foo.db")

# Windows alternative using raw string
engine = create_engine(r"sqlite:///C:\path\to\foo.db")

참고 문서 : https://docs.sqlalchemy.org/en/20/core/engines.html#supported-databases

반응형

'프로그래밍 > Python' 카테고리의 다른 글

[PYTHON] 파이썬 함수 매개변수  (0) 2022.08.11
[Python] flask_restful fields  (0) 2021.10.08
Single Linked list 구현  (0) 2018.03.22
창원시 버스 API 사용하기  (1) 2016.02.22

+ Recent posts