postgresql Psycopg2 - AttributeError: 'NoneType' 对象没有属性 'fetchall'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32901686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Psycopg2 - AttributeError: 'NoneType' object has no attribute 'fetchall'
提问by Edward Samuel
I have a Python script to list PostgreSQL schemas using psycopg2.
我有一个 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())
When I run the script, I got:
当我运行脚本时,我得到:
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'
I thought the SQL query is OK. When I execute the query using another PostgreSQL client, it returned some rows. Why did the cursor.execute
return None
? Is there something wrong in my script?
我认为 SQL 查询没问题。当我使用另一个 PostgreSQL 客户端执行查询时,它返回了一些行。为什么cursor.execute
回来了None
?我的脚本有问题吗?
回答by ozgur
.execute()
just executes the query and does not return anything. It is up to you how you are going to fetch the results (ex: iterator, fetchall(), fetchone() etc.)
.execute()
只执行查询,不返回任何内容。如何获取结果取决于您(例如:迭代器、fetchall()、fetchone() 等)
>>> cursor.execute(sql_list_schemas)
>>> list_schemas = cursor.fetchall()
--
——
Similarly,
相似地,
>>> cursor.execute(sql_list_schemas)
>>> first_row = cursor.fetchone()
>>> second_row = cursor.fetchone()
>>> remaining_rows = cursor.fetchall()
--
——
PEP-2049
states that return values are not defined for .execute()
method so database connectors may return something different than None
. (ex: a boolean flag indicating whether sql command has been successfully executed or not)
PEP-2049
声明未为.execute()
方法定义返回值,因此数据库连接器可能返回与None
. (例如:指示 sql 命令是否已成功执行的布尔标志)
However, one thing for sure, cursor.execute()
never returns the result set.
但是,可以肯定的是,cursor.execute()
永远不会返回结果集。