前言
sqlacodegen 安装
pip install sqlacodegen==2.3.0
mysql 指定导出表命令
# 指定表 导出 model sqlacodegen mysql+pymysql://user:password@127.0.0.1:3306/dbname --outfile=models.py
连接sql server数据库
sqlacodegen mssql+pymssql://user:password@host:port/dbname --outfile=models.py
连接sqlite
# 将数据库中所有表导出为 model sqlacodegen sqlite:///testdb.db --outfile=models.py
sqlacodegen 命令行参数-h查看
>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 database optional 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)
使用实例
数据库连接地址
# 拼接配置dialect + driver://username:passwor@host:port/database DB_URI = 'mysql+pymysql://root:123456@localhost:3306/web'
只想同步students 这张表的数据,执行命令
sqlacodegen mysql+pymysql://root:123456@localhost:3306/web --outfile=models.py --tables students
# coding: utf-8 from sqlalchemy import Column, String from sqlalchemy.dialects.mysql import INTEGER from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Student(Base): __tablename__ = 'students' id = Column(INTEGER(11), primary_key=True) name = Column(String(20)) fullname = Column(String(30)) nickname = Column(String(30))
如果命令不带--tables
参数,会生成所有的表
sqlacodegen mysql+pymysql://root:123456@localhost:3306/web --outfile=models.py
使用 autoload = True
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.schema import Table engine = create_engine("mysql+pymysql://root:123456@localhost:3306/web") Base = declarative_base() metadata = Base.metadata metadata.bind = engine class Employee(Base): __table__ = Table("employees", metadata, autoload=True)
这种方法我们看不到代码里面表字段名称,一般不推荐用。
原文来自:https://blog.csdn.net/qq_27371025/article/details/126440632
评论