使用SQLAlchemy元数据reflect()如何获得实际的表对象?

Ray*_*Ray 7 python sqlalchemy

我只是在现有数据库上做了很多选择.

  • 不要使用原始SQL,因为我可能想在mysql和sqlite之间跳转进行测试
  • 想要坚持使用SQLAlchemy的SQL Expression语言.

我需要得到一个Table对象,所以我做了类似的事情

 s = select([some_table_object])
Run Code Online (Sandbox Code Playgroud)

我已经想过如何显式地反映单个表来获取表对象:

from sqlalchemy import *

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

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

# HAPPY!!!!
Run Code Online (Sandbox Code Playgroud)

但是,由于必须为每个表执行此操作,因此这很繁琐(我会使用很多表).我知道我可以以某种方式使用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)
Run Code Online (Sandbox Code Playgroud)

更换线路mytable = metadata.no_clue_how_to_get_tables()以获取Table实例需要什么?

Ilj*_*ilä 7

它就像从元数据对象的表字典中查找表一样简单:

mytable = metadata.tables['mytable']
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅"一次反映所有表".

  • 有没有办法在使用“metadata.reflect(views=True)”时查询或过滤视图? (2认同)

Hal*_*lee 5

如果您不确定最初存在哪些表,可以执行此查询来检查数据库表。

from sqlalchemy import create_engine
from sqlalchemy.engine import reflection

# Create connection string & engine
connection_string = "sql_connection_string"
engine = create_engine(connection_string, echo=False)

# Performs database schema inspection
insp = reflection.Inspector.from_engine(engine)
print(insp.get_table_names())
Run Code Online (Sandbox Code Playgroud)

然后您可以从表中选择元数据,如上面的答案所示。

Inspector.get_table_names()返回特定模式中引用的所有表名。这不会返回视图。相反,视图是使用该Inspector.get_view_names()方法返回的。文档