首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python3 psycopg2:使用返回“没有要获取的结果”

Python3 psycopg2:使用返回“没有要获取的结果”
EN

Stack Overflow用户
提问于 2019-03-28 14:55:49
回答 1查看 4.3K关注 0票数 2

我在用:

  • psvcopg2
  • python3.6
  • postgresql-11.2
  • 库班图18.10

我成功地插入了一行,但是cursor.fetchall()引发了

代码语言:javascript
运行
复制
psycopg2.ProgrammingError: no results to fetch

即使在使用返回SQL中检索id时也是如此。

我发现了cursor.description,但它是空的(cursor.description、==、None)。

SQL在psql终端中正确使用,根据请求返回id。

python代码

代码语言:javascript
运行
复制
import psycopg2
from psycopg2.pool import ThreadedConnectionPool

pool = ThreadedConnectionPool(3, 20,
                              user="user",
                              password='xxxxxxxxx',
                              host="127.0.0.1",
                              port="5432",
                              database="my_database")

query = 'INSERT INTO market.item(item_store_id, title, price, url, image_url, aff_url, store_id) ' \
        'VALUES(%(item_store_id)s, %(title)s, %(price)s, %(url)s, %(image_url)s, %(aff_url)s, %(store_id)s) ' \
        'ON CONFLICT (item_store_id) DO ' \
        'UPDATE SET (price, url, image_url, aff_url) = (excluded.price, excluded.url, excluded.image_url, excluded.aff_url) ' \
        'RETURNING item_id '
args = [{
    'item_store_id': 1,
    'title': 'My title',
    'price': 15,
    'url': 'http://www.url.com',
    'image_url': 'http://www.url.com',
    'aff_url': 'http://www.url.com',
    'store_id': 1,
}]
try:
    result = []
    connection = pool.getconn()
    connection.autocommit = True
    with connection.cursor() as cursor:
        try:
            cursor.executemany(query, args)
            if cursor.rownumber > 0:
                subresult = cursor.fetchall()
                result.append(subresult)

            print(result)
        except (Exception, psycopg2.DatabaseError) as e:
            raise
except (Exception, psycopg2.DatabaseError) as error:
    print(e)
else:
    print(result)
finally:
    pool.putconn(connection)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-29 13:46:31

是我的错。我在文档里没注意到这个:

代码语言:javascript
运行
复制
The function is mostly useful for commands that update the database: any result set returned by the query is discarded.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55400707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档