• 三十八:数据库之ORM层面删除数据的注意事项


    准备工作

    from sqlalchemy import create_engine, Column, Integer, String, Float, Text, ForeignKey
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker, relationship, backref

    # 数据库信息
    host = '127.0.0.1'
    port = '3306'
    database = 'db_to_sqlalchemy'
    username = 'root'
    password = '123456'

    # 数据库类型+连接数据库的插件,这里使用的pymysql
    DB_URI = f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}'

    engine = create_engine(DB_URI) # 创建引擎
    Base = declarative_base(engine) # 使用declarative_base创建基类
    session = sessionmaker(engine)()

    创建模型

    class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), nullable=False)

    def __repr__(self):
    return f'User(username: {self.username})'


    class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(50), nullable=False)
    uid = Column(Integer, ForeignKey('user.id'))

    author = relationship('User', backref='article')

    def __repr__(self):
    return f'Article(title: {self.title})'


    Base.metadata.drop_all() # 删除所有表
    Base.metadata.create_all() # 创建表

    插入数据

    user = User(username='aaa')
    article = Article(title='xxxxxxx')
    article.author = user

    session.add(article)
    session.commit()

    写SQL删除user信息,报外键约束

    使用sqlalchemy删除,成功

    user = session.query(User).first()
    session.delete(user)
    session.commit()

    可见,sqlalchemy删除时会将外键设置为null,所以为了使用外键约束,需在建表的时候,设置外键nullable=False,即不允许为空

    class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), nullable=False)

    def __repr__(self):
    return f'User(username: {self.username})'


    class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(50), nullable=False)
    uid = Column(Integer, ForeignKey('user.id'), nullable=False)

    author = relationship('User', backref='article')

    def __repr__(self):
    return f'Article(title: {self.title})'


    Base.metadata.drop_all() # 删除所有表
    Base.metadata.create_all() # 创建表

    user = User(username='aaa')
    article = Article(title='xxxxxxx')
    article.author = user

    session.add(article)
    session.commit()

    再次删除,就会报错

    user = session.query(User).first()
    session.delete(user)
    session.commit()
  • 相关阅读:
    博客链接--竹子
    升级sudo至1.9.5p2,修复sudo漏洞
    使用Jenkins自动打包部署前端
    升级sudo至1.9.5p2,修复sudo漏洞
    60行C代码实现一个shell
    copy_{to, from}_user()的思考
    Code Server 是什么?
    Linux常用命令学习(5)
    Linux sudo权限提升漏洞(CVE-2021-3156)
    厚书读薄丨《Vim实用技巧》第一部分 模式
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11816432.html
Copyright © 2020-2023  润新知