准备工作
from sqlalchemy import create_engine, Column, Integer, String, Float, Text, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 数据库信息
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=Float)
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)
content = Column(Text, nullable=Float)
uid = Column(Integer, ForeignKey('user.id'))
def __repr__(self):
return f'Article(title:{self.title}, content:{self.content})'
Base.metadata.create_all()
user = User(username='aa')
session.add(user)
session.commit()
article = Article(title='title2', content='123', uid=1)
session.add(article)
session.commit()
通过文章拿user信息
不使用外建查询方法
使用外建:relationship
通过user拿对应uid的文章信息
以上方式需要在有外建关系的模型中都加relationship,比较麻烦,sqlalchemy提供了一个反向引用的方法:backref
同样可以通过articles反向查找
使用一对多插入数据
反向添加:把user添加到从表