当前位置:首页 > Python > 正文内容

SQLAlchemy中使用sqlacodegen自动同步数据库中表生成model

lonely1年前 (2022-11-29)Python1414

前言

如果数据库中的表已经存在了,我们只想通过 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)

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


原文来自:https://blog.csdn.net/qq_27371025/article/details/126440632

扫描二维码推送至手机访问。

版权声明:本文由复制者发布,如需转载请注明出处。

本文链接:https://www.copyer.cn/post/32.html

分享给朋友:

相关文章

locustio安装失败,提示: ERROR: Command errored out with exit status 1:

locustio安装失败,提示: ERROR: Command errored out with exit status 1:

使用pip install locustio 和 pip install -i https://pypi.douban.com/simple locustio 安装时均失败,提示:C:\Us...

python-selenium弹框处理driver.switch_to.alert

python-selenium弹框处理driver.switch_to.alert

三种弹出框alert(一个按钮),confirm(两个确认,取消),prompt(两个按钮+输入框) 使用示例:ele_alert = driver.switch_to....

详解python的xlwings库读写excel操作总结

详解python的xlwings库读写excel操作总结

 一、总结一句话总结:xlwings 是 Python 中操作Excel的一个第三方库,支持.xls读写,.xlsx读写,操作非常简单,功能也很强大1、xlwings 中的逻辑:应用->...

python使用国内镜像源安装更新模块

python使用国内镜像源安装更新模块

由于python更新源速度较慢,且经常更新失败。国内更新源可秒更,以下是配置方法。1、python2.7更新pip命令1python -m pip install --upgrad...

Python pip更换安装源

Python pip更换安装源

常见的镜像源:华为:https://repo.huaweicloud.com/repository/pypi/simple 清华:https://pypi.tuna.tsinghua.edu...

推荐一个好用的Python第三方日志库loguru

推荐一个好用的Python第三方日志库loguru

        Loguru: 更优雅的日志记录解决方案loguru 是一个 Python 简易且强大的第三方日志记录库...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。