从现有的MySQL数据库反向工程师SQLAlchemy声明性类定义? [英] Reverse engineer SQLAlchemy declarative class definition from existing MySQL database?

查看:143
本文介绍了从现有的MySQL数据库反向工程师SQLAlchemy声明性类定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预先存在的mysql数据库,其中包含约50个表.

I have a pre-existing mysql database containing around 50 tables.

而不是手工编写声明式SqlAlchemy类(如此处所示),是否存在我可以针对将生成 python类的mysql数据库运行的工具/脚本/命令数据库中每个表的声明式样式?

Rather than hand code a declarative style SqlAlchemy class (as shown here) for each table, is there a tool/script/command I can run against the mysql database that will generate a python class in the declarative style for each table in the database?

仅以一个表为例(理想情况下,将为所有50个表生成),如下所示:

To take just one table as an example (would generate for all 50 ideally) as follows:

+---------+--------------------+
| dept_no | dept_name          |
+---------+--------------------+
| d009    | Customer Service   |
| d005    | Development        |
| d002    | Finance            |
| d003    | Human Resources    |
| d001    | Marketing          |
| d004    | Production         |
| d006    | Quality Management |
| d008    | Research           |
| d007    | Sales              |
+---------+--------------------+

有没有可以生成包含以下内容的文本文件的工具/脚本/命令:

Is there a tool/script/command that can generate a text file containing something like:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Department(Base):
   __tablename__ = 'departments'

   dept_no = Column(String(5), primary_key=True)
   dept_name = Column(String(50))

   def __init__(self, dept_no, dept_name):
       self.dept_no = dept_no
       self.dept_name = dept_name

   def __repr__(self):
      return "<Department('%s','%s')>" % (self.dept_no, self.dept_name)

推荐答案

使用 sqlautocode :

这是一个灵活的工具,可以从现有数据库中自动生成模型.

It is a flexible tool to autogenerate a model from an existing database.

这与 SqlSoup 的方法稍有不同,该方法使您无需显式使用表定义它们.另一方面,sqlalutocode将生成实际的python代码.

This is a slightly different approach to SqlSoup, which lets you use tables without explicitly defining them. On the other hand, sqlalutocode will generate actual python code.

这篇关于从现有的MySQL数据库反向工程师SQLAlchemy声明性类定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆