准备工作
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()