1、安装sqlacodegen
pip install sqlacodegen
pip install pymysql
2、导出指定数据表
- 单表
sqlacodegen mysql+pymysql://root:password@127.0.0.1:3306/test --tables user --outfile user.py
- 多表
sqlacodegen mysql+pymysql://root:password@127.0.0.1:3306/test --tables user,iterm --outfile models.py
- 导出整个数据库
sqlacodegen mysql+pymysql://root:password@127.0.0.1:3306/test --outfile=models.py
3、sqlacodegen 参数说明
# --schema SCHEMA load tables from an alternate schema # 指定表,默认是全部的表
# -tables TABLES tables to process (comma-separated, default: all)
# noviews ignore views
# noclasses don't generate classes, only tables
# 指定生成模型类文件
# outfile OUTFILE file to write output to (default: stdout>sqlacodegen -h
usage: sqlacodegen [-h] [--version] [--schema SCHEMA] [--tables TABLES] [--noviews] [--noindexes][--noconstraints] [--nojoined] [--noinflect] [--noclasses] [--nocomments][--outfile OUTFILE][url]Generates SQLAlchemy model code from an existing database.positional arguments:url SQLAlchemy url to the databaseoptional arguments:-h, --help show this help message and exit--version print the version number and exit--schema SCHEMA load tables from an alternate schema--tables TABLES tables to process (comma-separated, default: all)--noviews ignore views--noindexes ignore indexes--noconstraints ignore constraints--nojoined don't autodetect joined table inheritance--noinflect don't try to convert tables names to singular form--noclasses don't generate classes, only tables--nocomments don't render column comments--outfile OUTFILE file to write output to (default: stdout)
sqlacodegen 是命令级别,添加模型类以及构建拓展类 可以结合 subprocess 或 os 模块进行脚本化操作
4、生成SQLite数据库模型
from sqlalchemy import create_engineengine = create_engine('sqlite:///mydatabase.db')
from models import Base, User# 创建表
Base.metadata.create_all(engine)# 插入数据
user = User(name='John Doe', email='johndoe@example.com')
session.add(user)
session.commit()# 查询数据
users = session.query(User).all()
for user in users:print(user.name, user.email)
使用sqlacodegen生成模型代码:
sqlacodegen sqlite:///mydatabase.db --outfile models.py