前置工作
安装如下工具
Python 3.5.2
Sqlalchemy
mysql-connector, pymysql, mysql-python其中一个
源代码
from sqlalchemy import Column, String, create_engine, Table, MetaData, Integer, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship, foreign, remote
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine("mysql+mysqlconnector://root:123456@localhost:3306/test")
Base = declarative_base() # 生成orm基类
topic_label = Table("topic_label", Base.metadata,
Column("topic_id", Integer, primary_key=True),
Column("label_id", Integer, primary_key=True)
)
class Label(Base):
__tablename__ = "label"
id = Column(Integer, primary_key=True)
name = Column(String(20))
class Topic(Base):
__tablename__ = "topic"
id = Column(Integer, primary_key=True)
name = Column(String(20))
labels = relationship("Label", primaryjoin=id == topic_label.c.topic_id,
secondaryjoin=Label.id == topic_label.c.label_id,
secondary=topic_label,
backref="topics",
)
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()
topic1 = Topic(id=1, name="第一个话题")
topic2 = Topic(id=2, name="第二个话题")
topic3 = Topic(id=3, name="第三个话题")
label1 = Label(id=1, name="第一个标签")
label2 = Label(id=2, name="第二个标签")
label3 = Label(id=3, name="第三个标签")
# Label.topics 和Topic.labels 可以看做是一个列表,往里面加入对象时,可能会同时影响3张表
# 将topic2添加入label.topics中
label2.topics.append(topic2)
session.add(label2)
session.commit()
# 将label3添加入topic3.labels中
# 过程: 创建了一个topic3,并且把label3贴给topic3,于是表topic、label和中间表topic_label都创建了一条数据
topic3.labels.append(topic3)
session.add(topic3)
session.commit()
sqlalchemy库介绍
sqlalchemy.orm 储存了定义一些通过ORM访问数据库的相关内容
sqlalchemy.* 定义了许多构建数据库的相关内容
sqlalchemy.ext.declarative 主要用到declarative_base,用于创建数据库Model的基类
网友评论