Reputation: 4919
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.
Upvotes: 5
Views: 5170
Reputation: 302
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:
pip install sqlacodegen
pip install pymssql
sqlacodegen mssql+pymssql://sql_username:sql_password@server/database > db_name.py
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.
Upvotes: 7
Reputation: 2493
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.
Upvotes: 2