进入我的postgres数据库,显示目标数据库中的所有表:
psql -U postgres
Pager usage is off.
Timing is on.
psql (13.10 (Debian 13.10-0+deb11u1))
Type "help" for help.
postgres=# \c target
You are now connected to database "target" as user "postgres".
target=# \d
List of relations
Schema | Name | Type | Owner
--------+--------+-------+----------
public | pe | table | postgres
public | sector | table | postgres
public | subnew | table | postgres
target
数据库中有三个表。我想用sqlalchemy列出所有的表。
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table
db_pass = 'xxxxxx'
db_ip='127.0.0.1'
engine = create_engine('postgresql://postgres:{}@{}/target'.format(db_pass,db_ip))
# Create MetaData instance
metadata = MetaData(engine).reflect()
print(metadata.tables)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'tables'
如何使用sqlalchemy列出postgres数据库中的所有表?
1条答案
按热度按时间svmlkihl1#
利用sqlalchemy模块e中的
inspect
函数。例如:https://docs.sqlalchemy.org/en/20/core/reflection.html#sqlalchemy.engine.reflection.Inspector