【发布时间】:2015-10-02 06:34:12
【问题描述】:
我有一个 Python 脚本来使用 psycopg2 列出 PostgreSQL 模式。
#!/usr/bin/env python
import yaml
import psycopg2
def load_config(file_name):
with open(file_name, 'r') as stream:
config = yaml.load(stream)
return config
config = load_config('config.yml')['database']
conn = psycopg2.connect(host=config['host'], port=config['port'], dbname=config['name'], user=config['user'], password=config['password'])
cursor = conn.cursor()
print('conn = %s' % conn)
print('cursor = %s' % cursor)
sql_list_schemas = """
SELECT *
FROM information_schema.schemata
WHERE schema_name <> 'information_schema'
AND schema_name !~ E'^pg_';
"""
list_schemas = cursor.execute(sql_list_schemas)
print('list_schemas = %s' % list_schemas)
print('list_schemas.fetchall() = %s' % list_schemas.fetchall())
当我运行脚本时,我得到:
conn = <connection object at 0x7f0e12eef050; dsn: 'user=test password=xxxxxxxxxxxxx host=127.0.0.1 port=5432 dbname=test', closed: 0>
cursor = <cursor object at 0x7f0e1326c148; closed: 0>
list_schemas = None
Traceback (most recent call last):
File "./postgres_db_schema.py", line 26, in <module>
print('list_schemas.fetchall() = %s' % list_schemas.fetchall())
AttributeError: 'NoneType' object has no attribute 'fetchall'
我认为 SQL 查询没问题。当我使用另一个 PostgreSQL 客户端执行查询时,它返回了一些行。为什么cursor.execute 返回None?我的脚本有问题吗?
【问题讨论】:
标签: python postgresql psycopg2