添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
from datetime import datetime

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

# 数据库信息
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'username: {self.username}'


class Article(Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), nullable=False)
create_time = Column(DateTime, nullable=False, default=datetime.now)
uid = Column(Integer, ForeignKey('user.id'))
author = relationship('User', backref='article')

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


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

user1 = User(username='user1')
for x in range(1):
article = Article(title=f'title{x}')
article.author = user1
session.add(article)
session.commit()

user2 = User(username='user2')
for x in range(1, 3):
article = Article(title=f'title{x}')
article.author = user2
session.add(article)
session.commit()

找到所有用户,按照文章数量进行排序

SQL语句实现

SQLAlchemy实现

由于已经使用了外建,所以会自动将User.id与Article.uid关联