sqlalchemy1.4风格2.0

x33g5p2x  于2022-02-28 转载在 其他  
字(2.9k)|赞(0)|评价(0)|浏览(389)

1 基本配置

官方文档:
https://docs.sqlalchemy.org/en/14/orm/session_basics.html#session-querying-20

1.1 Model

  1. from sqlalchemy import INTEGER, Column, ForeignKey, String
  2. from sqlalchemy.orm import declarative_base, relationship
  3. Base = declarative_base()
  4. class Users(Base):
  5. __tablename__ = "users"
  6. uid = Column(INTEGER, primary_key=True)
  7. name = Column(String(30))
  8. age = Column(INTEGER)
  9. class Article(Base):
  10. __tablename__ = "article"
  11. a_id = Column(INTEGER, primary_key=True)
  12. uid = Column(INTEGER)
  13. a_title = Column(String(30))
  14. a_readcount = Column(INTEGER)

1.2 映射

  1. from sqlalchemy import create_engine
  2. from sqlalchemy.orm import sessionmaker
  3. from model import Base
  4. # 建立与MySQL的连接
  5. db_name = "sanic_test"
  6. host = "127.0.0.1"
  7. db_user = "root"
  8. password = "root"
  9. engine = create_engine(f'mysql+pymysql://{db_user}:{password}@{host}/{db_name}', echo=True)
  10. # 创建session对象
  11. session = sessionmaker(engine)()
  12. # 创建表,执行所有BaseModel类的子类
  13. Base.metadata.create_all(engine)
  14. # 提交,必须
  15. session.commit()

1.3 main

  1. from sqlalchemy import create_engine, select
  2. from sqlalchemy.orm import Session
  3. from model import Users, Article
  4. engine = create_engine('mysql://root:root@127.0.0.1/sanic_test?charset=utf8')
  5. session = Session(engine, future=True)

2 数据库

  1. mysql> select * from users;
  2. +-----+--------------+-----+
  3. | uid | name | age |
  4. +-----+--------------+-----+
  5. | 1 | 有勇气的牛排 | 20 |
  6. | 2 | 灰太狼 | 20 |
  7. +-----+--------------+-----+
  1. mysql> select * from article;
  2. +------+-----+---------+-------------+
  3. | a_id | uid | a_title | a_readcount |
  4. +------+-----+---------+-------------+
  5. | 1 | 1 | python | 10 |
  6. | 2 | 1 | java | 30 |
  7. | 3 | 2 | vue | 15 |
  8. +------+-----+---------+-------------+

3 异常处理

  1. with Session(engine) as session:
  2. session.begin()
  3. try:
  4. session.add(some_object)
  5. session.add(some_other_object)
  6. except:
  7. session.rollback()
  8. raise
  9. else:
  10. session.commit()

结合写法

  1. with Session(engine) as session, session.begin():
  2. session.add(some_object)
  3. session.add(some_other_object)

4 使用 sessionmaker

  1. from sqlalchemy.orm import sessionmaker
  1. engine = create_engine('postgresql://scott:tiger@localhost/')
  2. # a sessionmaker(), also in the same scope as the engine
  3. Session = sessionmaker(engine)

3 增加数据

没有的列,自动为空

  1. user1 = Users(name="战神")
  2. user2 = Users(name="战神2", age=18)
  3. session.add(user1)
  4. session.add(user2)
  5. session.commit()

要一次将项目列表添加到会话中,可以使用 Session.add_all()

  1. session.add_all([user1, user2])

4 删除

5 更新

  1. stmt = update(Users).where(Users.uid == 7).values(name="大哥").\
  2. execution_options(synchronize_session="fetch")
  3. result = session.execute(stmt)

execution_options():可用于建立执行时间选项

5 查询

5.1 查询单表 多个记录

  1. statement = select(Users).filter_by(age=20)
  2. result = session.execute(statement).scalars().all()
  3. print(result)
  4. for i in result:
  5. print(i)
  6. print(i.id)
  7. print(i.name)
  8. print(i.age)

5.2 查询多表 多个记录

  1. statement = select(Users, Article).where(Users.uid == Article.uid)
  2. result = session.execute(statement).all()
  3. print(result)
  4. for users, article in result:
  5. print(users.uid, article.a_title)

5.3 指定列

  1. statement = select(Users.uid, Users.name, Article).where(Users.uid == Article.uid)
  2. result = session.execute(statement).all()
  3. print(result)
  4. for uid, name, article in result:
  5. print(uid, name, article.a_title)

相关文章