ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

SQLAlchemy学习-3.(懒人专用)sqlacodegen自动同步数据库中表生成model 代码

2022-07-14 16:33:56  阅读:209  来源: 互联网

标签:tables SQLAlchemy sqlacodegen -- outfile Base mysql model


前言

如果数据库中的表已经存在了,我们只想通过 SQLAlchemy 操作数据库表的数据,不需要建表。
这时可以不用一个个声明每个字段类型,可以用第三方包 sqlacodegen 自动生成 model 模型代码。

sqlacodegen 安装

使用pip安装对应包

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)

使用实例

比如我在mysql数据库中有一张表,结构如下

数据库连接地址

# 拼接配置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

相关参数说明:
--outfile 指定导出模块名称models.py
--tables 指定导出的表名称,多个表用逗号隔开,不指定导出全部表

执行后得到models.py,内容如下

# 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

还有一种方法可以让模型代码跟数据库表字段关联起来,__table__ 中使用 autoload = True
它会自动加载 model 的 Column, 使用这种方法时,在构建 model 之前,Base 类要与 engine 进行绑定.

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)

这种方法我们看不到代码里面表字段名称,一般不推荐用。

标签:tables,SQLAlchemy,sqlacodegen,--,outfile,Base,mysql,model
来源: https://www.cnblogs.com/yoyoketang/p/16478175.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有