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

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

lonely2年前 (2022-11-29)Python1871

前言

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

分享给朋友:

相关文章

python-selenium设置webdriver隐藏浏览器运行及不加载图片

python-selenium设置webdriver隐藏浏览器运行及不加载图片

from selenium import webdriver # 设置无界面 opt = webdriver.ChromeOpt...

python获取基础路径供其他模块导入

python获取基础路径供其他模块导入

# 文件1:获取基础路径,供其他文件导入,当前文件是conf/settings.py文件 import os base_path = os.path.d...

详解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获取昨天的日期

python获取昨天的日期

import datetime def getYesterday():     today = datetime.d...

windows更换conda源

windows更换conda源

使用清华源一、cmd中执行conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/an...

发表评论

访客

看不清,换一张

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