SQLAlchemy 是Python中最有名的ORM框架。mysql
安裝SQLAlchemy:sql
$ pip install sqlalchemy
導入SQLAlchemy,並初始化DBSession:數據庫
from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # 建立對象的基類: Base = declarative_base() # 定義User對象: class User(Base): # 表的名字: __tablename__ = 'user' # 表的結構: id = Column(String(20), primary_key=True) name = Column(String(20)) # 初始化數據庫鏈接: engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/test') # 建立DBSession類型: DBSession = sessionmaker(bind=engine)
向數據庫表中添加一行記錄:session
# 建立session對象: session = DBSession() # 建立新User對象: new_user = User(id='5', name='Bob') # 添加到session: session.add(new_user) # 提交即保存到數據庫: session.commit() # 關閉session: session.close()
查詢數據:框架
# 建立Session對象: session = DBSession() # 建立Query查詢: user = session.query(User).filter(User.id=='5').one() # 打印類型和對象的name屬性: print('type:', type(user)) print('name:', user.name) # 關閉Session: session.close()
定義一對多關係以下:code
class User(Base): __tablename__ = 'user' id = Column(String(20), primary_key=True) name = Column(String(20)) # 一對多: books = relationship('Book') class Book(Base): __tablename__ = 'book' id = Column(String(20), primary_key=True) name = Column(String(20)) # 「多」的一方的是經過外鍵關聯到user表的: user_id = Column(String(20), ForeignKey('user.id'))