How can I autogenerate ORM code for SQLAlchemy when consuming TSQL (mssql on SQL Server) from python?

試著忘記壹切 提交于 2020-06-16 04:55:31

问题


SQLAlchemy relies on me building ORM classes like this:

from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
    __tablename__ = 'department'
    id = Column(Integer, primary_key=True)
    name = Column(String)

Is there a tool/script/program than can do this for me?

For instance, in C# I can just drag and drop data items from the Database explorer into VisualStudio and have Entity Classes autogenerated for me (SQL to LINQ). I'm looking for something similar for python. I'm working in VisualStudio and/or Spyder.


回答1:


I just successfully used sqlacodegen to generate the classes for my MS SQL Server 2014 database. It was super easy; I instantly fell in love with it!

I'm using Python 3.7 (if it matters). Here are the commands I used in (an administrator?) PowerShell:

  1. pip install sqlacodegen
  2. pip install pymssql
  3. sqlacodegen mssql+pymssql://sql_username:sql_password@server/database > db_name.py
  4. It will create db_name.py in your current directory.
  5. You can then use those classes by moving db_name.py to the same folder as your main script and adding import db_name.

I did not specify a port and my server is setup to simply be the computer's name without specifying the installation, i.e. server\installation. I used the instructions for sqlacodegen here and the database URL from here.




回答2:


Do you need to have the classes explicitly defined, or would having them defined without writing the code work okay? If the latter is okay, then SQLAlchemy's own automap might be enough.

Otherwise, the sqlacodegen tool looks like it should do code generation for you.



来源:https://stackoverflow.com/questions/42808230/how-can-i-autogenerate-orm-code-for-sqlalchemy-when-consuming-tsql-mssql-on-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!