1

I am coming from a place where the database designer/administrator gives you a MySQL database already designed with all the tables together with the functions, triggers etc and all you have to do is perform CRUD on the tables.

So i was wondering if there was a way to use sqlachemy to map to the already designed tables and use the sqlachemy methods to perform CRUD on the tables without me having necessarily to create the tables from my python code (because I don't have the permissions to) basically avoiding the step below:

metadata = MetaData()
books = Table('book', metadata,
  Column('id', Integer, primary_key=True),
  Column('title', String),
  Column('primary_author', String),
)

engine = create_engine('sqlite:///bookstore.db')
metadata.create_all(engine)

Note: I am using an sqlite example just to make my point. Thank you

LeCodex
  • 1,636
  • 14
  • 20
kellymandem
  • 1,709
  • 3
  • 17
  • 27

1 Answers1

2

Hi have you take a look at the Automap of SQLAlchemy. It might do the trick

Apparently, it seems that it is not enough so :

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

Base = automap_base()

# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("sqlite:///mydatabase.db")

# reflect the tables
Base.prepare(engine, reflect=True)

# mapped classes are now created with names by default
# matching that of the table name.
User = Base.classes.user
Address = Base.classes.address

And then you can do, directly, your CRUD operations like adding, updating, etc ...

Jrmyy
  • 151
  • 8