python – Psycopg2 – AttributeError:’NoneType’对象没有属性’fetchall’
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – Psycopg2 – AttributeError:’NoneType’对象没有属性’fetchall’,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1851字,纯文字阅读大概需要3分钟。
内容图文
我有一个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?我的剧本有什么问题吗?
解决方法:
.execute()只执行查询而不返回任何内容.取决于你如何获取结果(例如:iterator,fetchall(),fetchone()等).
>>> cursor.execute(sql_list_schemas)
>>> list_schemas = cursor.fetchall()
–
同样的,
>>> cursor.execute(sql_list_schemas)
>>> first_row = cursor.fetchone()
>>> second_row = cursor.fetchone()
>>> remaining_rows = cursor.fetchall()
–
PEP-2049声明没有为.execute()方法定义返回值,因此数据库连接器可能返回与None不同的值. (例如:一个布尔标志,指示sql命令是否已成功执行)
但是,有一点可以肯定,cursor.execute()永远不会返回结果集.
内容总结
以上是互联网集市为您收集整理的python – Psycopg2 – AttributeError:’NoneType’对象没有属性’fetchall’全部内容,希望文章能够帮你解决python – Psycopg2 – AttributeError:’NoneType’对象没有属性’fetchall’所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。