sqlalchemy的orm的一对多,正向查询,反向查询
flask的SQLAlchemy
"""
安装:
pip install sqlalchemy
"""
models.py
# pip install sqlalchemy
import datetime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
from sqlalchemy.orm import relationship
Base = declarative_base()
class Users(Base):
__tablename__ = 'users' # 数据库表名称
id = Column(Integer, primary_key=True) # id 主键
name = Column(String(32), index=True, nullable=False) # name列,索引,不可为空
age = Column(Integer)
#email = Column(String(32), unique=True)
#datetime.datetime.now#不能加括号,加了括号,以后永远是当前时间
#ctime = Column(DateTime, default=datetime.datetime.now)
#extra = Column(Text, nullable=True)
__table_args__ = (
# UniqueConstraint('id', 'name', name='uix_id_name'), #联合唯一
# Index('ix_id_name', 'name', 'email'), #索引
)
def __repr__(self): # 作用类似于__str__, 但是__repr__的作用更加底层,__str__则打印不出来
return self.name
class Hobby(Base):
__tablename__ = "hobby"
id = Column(Integer, primary_key=True)
catption = Column(String(50), default="双色球")
class Person(Base):
__tablename__ = "person"
nid = Column(Integer, primary_key=True)
name = Column(String(32))
#hobby指的是tablename而不是Hobby类名,
hobby_id = Column(Integer,ForeignKey("hobby.id"))
# 跟数据库没有关系,不会新增加字段,只能用于快速的链表查询操作
#relationship的第一个参数,是类名,第二个参数backref,用于反向查询
hobby =relationship("Hobby", backref="pres")
def __repr__(self):
return self.name
def init_db():
"""
根据类创建数据库表
:return:
"""
engine = create_engine(
"mysql+pymysql://root:123456@127.0.0.1:3306/python13?charset=utf8",
#"什么数据库(mysql,orcal)+用什么取链接数据库(pymysql)://数据库用户名:密码@mysqlip:端口/数据库名?charset=字符集"
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
Base.metadata.create_all(engine)
def drop_db():
"""
根据类删除数据库表
:return:
"""
engine = create_engine(
"mysql+pymysql://root:123456@127.0.0.1:3306/python13?charset=utf8",
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
Base.metadata.drop_all(engine)
if __name__ == '__main__':
drop_db()
init_db()
orm的一对多
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Hobby,Person
# 你想要通过哪种方式连接前提是你必须得有相对应的插件,比如pymysql
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/python13", max_overflow=0, pool_size=5)
Connection = sessionmaker(bind=engine)
# 每次执行数据库操作时,都需要创建一个Connection
session = Connection()
#1添加,没有用关联关系
session.add_all([
Hobby(catption="淫诗"),
Hobby(catption="推背"),
Person(name="tank",hobby_id=1),
Person(name="jason",hobby_id=2)
])
# 2添加 用关联关系
person = Person(name="egon", hobby=Hobby(catption="相亲"))
session.add(person)
hobb = Hobby(catption="人妖")
hobb.pres = [Person(name="owen"), Person(name="sean")]
session.add(hobb)
session.commit()
#正向查询
pr = session.query(Person).filter( Person.name == "tank").first()
print(pr.name)
print(pr.hobby.catption)
#反向查
v = session.query(Hobby).filter(Hobby.catption=="人妖").first()
print(v.catption)
# print(v.pres)
# 自己连表,isouter=True表示是left join,如果想要right,你就把两个位置换下就OK了 不填默认为inner join
person_list = session.query(Hobby).join(Person, Person.hobby_id == Hobby.id, isouter=True)
# print(person_list)
session.close()
Only you can control your future
You're not alone. You still have family,peopel who care for you and want to save you.