Answer a question

I'm just doing a bunch of selects on an existing DB.

  • Don't want to use raw SQL as I may want to jump between MySQL and SQLite for testing
  • Want to stick to SQLAlchemy's SQL Expression language.

I need to get a Table object so I do something like:

 s = select([some_table_object])

I've figured how to explicitly reflect a single table to get a table object:

from sqlalchemy import *

conn = create_engine('mysql://....')
metadata = MetaData(conn)
mytable = Table('mytable', metadata, autoload=True)

s = select([mytable])
result = conn.execute(s)

# HAPPY!!!!

However, this gets tedious as you have to do it for each table (I go lots of tables). I know I can somehow use the MetaData class to reflect the existing DB I'm connecting to, but I'm unsure of how to get the actual corresponding Table from the metadata.

from sqlalchemy import *

conn = create_engine('mysql://....')

metadata = MetaData(conn)
metadata.reflect()

# How would do I get a Table instance corresponding to the 
# mytable table in the DB so I move on to HAPPY!!

mytable = metadata.no_clue_how_to_get_tables()

s = select([some_table_object])
result = conn.execute(s)

What's needed to replace the line mytable = metadata.no_clue_how_to_get_tables() to get a Table instance?

Answers

It is as simple as looking up the tables from the metadata object's dictionary of tables:

mytable = metadata.tables['mytable']

See "Reflecting All Tables At Once" for further info.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐