使用SQLAlchemy无法列出PostgreSQL表?求正确实现方法
如何用SQLAlchemy列出PostgreSQL数据库中的所有表?
首先通过psql操作确认target数据库包含三张表:
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
尝试用SQLAlchemy编写代码时触发AttributeError: 'NoneType' object has no attribute 'tables'错误,原代码如下:
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)
错误原因
MetaData.reflect()是原地修改MetaData对象的方法,不会返回新的实例,因此metadata = MetaData(engine).reflect()会将None赋值给metadata,导致无法访问tables属性。
正确实现方式
方法一:使用MetaData
先创建MetaData实例,再调用reflect方法绑定表信息:
from sqlalchemy import create_engine from sqlalchemy import MetaData db_pass = 'xxxxxx' db_ip='127.0.0.1' engine = create_engine('postgresql://postgres:{}@{}/target'.format(db_pass,db_ip)) # 创建MetaData实例 metadata = MetaData() # 绑定数据库表信息 metadata.reflect(bind=engine) # 打印所有表的键值对(表名: Table对象) print(metadata.tables) # 若只需表名列表,可使用: print(list(metadata.tables.keys()))
方法二:使用Inspector(更直观)
SQLAlchemy的Inspector工具可直接获取数据库元数据,适合快速查询表名:
from sqlalchemy import create_engine from sqlalchemy.inspect import inspect db_pass = 'xxxxxx' db_ip='127.0.0.1' engine = create_engine('postgresql://postgres:{}@{}/target'.format(db_pass,db_ip)) # 创建Inspector实例 inspector = inspect(engine) # 获取public schema下的所有表名 table_names = inspector.get_table_names(schema='public') print(table_names) # 若需遍历所有schema的表: schemas = inspector.get_schema_names() for schema in schemas: print(f"Schema: {schema}") print(f"Tables: {inspector.get_table_names(schema=schema)}")
内容的提问来源于stack exchange,提问作者showkey
相关产品推荐
相关产品推荐

