简体   繁体   English

映射 SQLAlchemy Core 上的所有表

[英]Mapping all tables on SQLAlchemy Core

A dumb question but I couldn't get why it does not work.一个愚蠢的问题,但我不明白为什么它不起作用。 I have a DB with several tables.我有一个有几个表的数据库。 I can map it manually我可以手动映射

Earnings = Table ('Earnings', metadata, autoload=True, autoload_with=engine)

or automatically using a loop.或自动使用循环。

tablenames = inspect(engine).get_table_names()
for tabname in tablenames:
    tabname = Table (tabname, metadata, autoload=True, autoload_with=engine)

I can use this code to see the mapped tables :我可以使用此代码查看映射表:

for tab in metadata.tables:
    print (tab)
...
>>> Earnings
...

So far, no problem.到目前为止,没有问题。

The question is that if try use the automatically mapped tables, it does not locate it.问题是如果尝试使用自动映射的表,它不会找到它。

Lista_colunas = Earnings.columns.items()
for col in Lista_colunas:
    print (col)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
c:\Users\fabio\Banco do Brasil S.A\DINED Parcerias Digitais - General\Python\Amazon\SQLA_Access_Test.ipynb Cell 13' in <cell line: 1>()
----> 1 Lista_colunas = Earnings.columns.items()
      2 for col in Lista_colunas:
      3     print (col)

NameError: name 'Earnings' is not defined

I realized that the auto mode is not creating the variables with the 'tabnames', but why not?我意识到自动模式不是用'tabnames'创建变量,但为什么不呢?

Somehow, VSCODE identifies that the 'Earnings' is a table objetc (see the picture), but does not let me call for it.不知何故,VSCODE 识别出“收益”是一个表对象(见图),但不允许我调用它。

VScode 鼠标悬停

Once the loop has completed, tabname will always be the table that corresponds to the final entry tin tablenames .循环完成后, tabname将始终是与最终条目 tin tablenames对应的表。 You could collect the tables in a dict keyed on tabname , but SQLAlchemy already provides a way to do this:您可以在以tabname为键的dict中收集表,但 SQLAlchemy 已经提供了一种方法来执行此操作:

metadata = MetaData()
metadata.reflect(bind=engine)  # Reflect all tables in the database.
Earnings = metadata.tables['Earnings']

The docs for reflection in general are here , the docs for MetaData.reflect are here .一般反射的文档在这里MetaData.reflect的文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM