[英]How can I autogenerate ORM code for SQLAlchemy when consuming TSQL (mssql on SQL Server) from python?
SQLAlchemy relies on me building ORM classes like this: SQLAlchemy依靠我来构建如下的ORM类:
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). 例如,在C#中,我可以将数据项从数据库浏览器拖放到VisualStudio中,并为我自动生成实体类(从SQL到LINQ)。 I'm looking for something similar for python.
我正在寻找类似的python。 I'm working in VisualStudio and/or Spyder.
我在VisualStudio和/或Spyder中工作。
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.
如果后者没问题,那么SQLAlchemy自己的自动映射可能就足够了。
Otherwise, the sqlacodegen tool looks like it should do code generation for you. 否则, sqlacodegen工具看起来应该为您执行代码生成。
I just successfully used sqlacodegen to generate the classes for my MS SQL Server 2014 database. 我刚刚成功使用sqlacodegen为我的MS SQL Server 2014数据库生成了类。 It was super easy;
超级容易。 I instantly fell in love with it!
我立即爱上了它!
I'm using Python 3.7 (if it matters). 我正在使用Python 3.7(如果有关系)。 Here are the commands I used in (an administrator?) PowerShell:
以下是我在(管理员?)PowerShell中使用的命令:
pip install sqlacodegen
pip install pymssql
sqlacodegen mssql+pymssql://sql_username:sql_password@server/database > db_name.py
import db_name
. 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, ie server\\installation
. 我没有指定端口,我的
server
设置为只是计算机的名称,而没有指定安装,即server\\installation
。 I used the instructions for sqlacodegen here and the database URL from here . 我在这里使用了sqlacodegen的说明,从这里使用了数据库URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.