三十八:数据库之ORM层面删除数据的注意事项
准备工作
from sqlalchemy import create_engine, Column, Integer, String, Float, Text, ForeignKeyfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmaker, relationship, backref# 数据库信息host = ‘127.0.0.1‘port = ‘3306‘database = ‘db_to_sqlalchemy‘username = ‘root‘password = ‘123456‘# 数据库类型+连接数据库的插件,这里使用的pymysqlDB_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 = usersession.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 = usersession.add(article)session.commit()
再次删除,就会报错
user = session.query(User).first()session.delete(user)session.commit()
相关推荐
技术之博大精深 2020-10-16
jimgreatly 2020-08-03
Lingforme 2020-07-18
chenjiazhu 2020-07-08
Yort 2020-06-28
zry 2020-06-28
技术之博大精深 2020-06-10
Lingforme 2020-06-10
jediaellu 2020-06-02
PengQ 2020-06-01
jediaellu 2020-05-31
Danialzhou 2020-05-30
shawroad 2020-05-30
tlsmile 2020-05-28
jediaellu 2020-05-28