SQLAlchemy是為Python程式語言提供的開源SQL工具包及對象關係對映器(ORM),是在MIT許可證下發行的軟件。

SQLAlchemy
原作者米高·拜爾(Michael Bayer)[1]
首次發佈2006年2月[2]
目前版本
  • 2.0.29 (2024年3月23日;穩定版本)[3]
編輯維基數據連結
原始碼庫 編輯維基數據連結
程式語言Python
作業系統跨平台
類型對象關係對映
許可協定MIT許可證
網站www.sqlalchemy.org

概述 編輯

SQLAlchemy提供企業級持久化英語Persistence (computer science)模式,首次發行於2006年2月。SQLAlchemy的理念是:關聯式資料庫隨着規模變大並且效能開始成為顧慮,而表現得不像對象搜集;而對象搜集隨着更多的抽象被設計入其中,而表現得不像表格。因此,SQLAlchmey採用了類似於JavaHibernate數據對映器模式[5],而不是其他ORM框架採用的主動記錄模式

範例 編輯

下述範例描述了電影同它們的導演之間的多對一聯絡。範例中說明了怎樣從用戶定義的Python建立對應的資料庫表格,怎樣從聯絡的任何一方建立有關聯的實例,最終怎樣查詢數據,演示了為延遲載入和預先載入二者自動生成的SQL查詢。

架構定義 編輯

建立兩個Python類以及在DBMS資料庫架構中對應的表格:

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, sessionmaker

Base = declarative_base()
 
class Movie(Base):
    __tablename__ = 'movies'
 
    id = Column(Integer, primary_key=True)
    title = Column(String(255), nullable=False)
    year = Column(Integer)
    directed_by = Column(Integer, ForeignKey('directors.id'))
 
    director = relation("Director", backref='movies', lazy=False)
 
    def __init__(self, title=None, year=None):
        self.title = title
        self.year = year
    def __repr__(self):
        return "Movie(%r, %r, %r)" % (self.title, self.year, self.director)
 
class Director(Base):
    __tablename__ = 'directors'
 
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False, unique=True)
 
    def __init__(self, name=None):
        self.name = name
 
    def __repr__(self):
        return "Director(%r)" % (self.name)
 
engine = create_engine('dbms://user:pwd@host/dbname')
Base.metadata.create_all(engine)

插入數據 編輯

電影與導演聯絡可以通過任何一方實體插入:

Session = sessionmaker(bind=engine)
session = Session()

m1 = Movie("Star Trek", 2009)
m1.director = Director("JJ Abrams")

d2 = Director("George Lucas")
d2.movies = [Movie("Star Wars", 1977), Movie("THX 1138", 1971)]

try:
    session.add(m1)
    session.add(d2)
    session.commit()
except:
    session.rollback()

查詢 編輯

alldata = session.query(Movie).all()
for somedata in alldata:
    print somedata

SQLAlchemy將向DBMS發起如下查詢(忽略別名):

SELECT movies.id, movies.title, movies.year, movies.directed_by, directors.id, directors.name 
FROM movies LEFT OUTER JOIN directors ON directors.id = movies.directed_by

輸出結果:

Movie('Star Trek', 2009L, Director('JJ Abrams'))
Movie('Star Wars', 1977L, Director('George Lucas'))
Movie('THX 1138', 1971L, Director('George Lucas'))

假如在架構定義時設置lazy=True(預設值),SQLAlchemy將首先發起一個查詢來獲得一個電影列表,並在必要時(延遲)對每個導演發起查詢來獲得對應導演的名字:

SELECT movies.id, movies.title, movies.year, movies.directed_by 
FROM movies

SELECT directors.id, directors.name
FROM directors 
WHERE directors.id = %s

參考文獻 編輯

  1. ^ Mike Bayer是SQLAlchmey以及Mako Templates for Python的创始人。. [2012-11-08]. (原始內容存檔於2012-10-26). 
  2. ^ PyCon 2007 Wrapup頁面存檔備份,存於互聯網檔案館),SQLAlchemy released 0.1.0 in February 2006 - O'Reilly Media
  3. ^ Release 2.0.29. 2024年3月23日 [2024年3月25日]. 
  4. ^ Releases - sqlalchemy/sqlalchemy. [8 August 2022]. (原始內容存檔於2021-07-18) –透過GitHub. 
  5. ^ 数据映射器. [2012-11-08]. (原始內容存檔於2012-11-04). 
註釋

參見 編輯

外部連結 編輯