python-3.x 为什么不能用sqlalchemy列出postgres数据库中的所有表?

vohkndzv  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(95)

进入我的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数据库中的所有表?

svmlkihl

svmlkihl1#

利用sqlalchemy模块e中的inspect函数。例如:

from sqlalchemy import create_engine, inspect

# Replace the following with your actual PostgreSQL connection string
connection_string = "postgresql://username:password@localhost/dbname"

engine = create_engine(connection_string)
inspector = inspect(engine)

# Get the list of table names
table_names = inspector.get_table_names()

# Print the table names
for table_name in table_names:
    print(table_name)

https://docs.sqlalchemy.org/en/20/core/reflection.html#sqlalchemy.engine.reflection.Inspector

相关问题