【问题标题】:Python3 psycopg2: "No results to fetch" using RETURNINGPython3 psycopg2:使用返回“没有要获取的结果”
【发布时间】:2019-03-28 14:55:49
【问题描述】:

我正在使用:

  • psvcopg2
  • python3.6
  • postgresql-11.2
  • kubuntu 18.10

我成功插入一行,但 cursor.fetchall() 正在提升

psycopg2.ProgrammingError: no results to fetch

即使我在 SQL 中使用 RETURNING 来检索 id。

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

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

python 代码

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)

【问题讨论】:

    标签: python python-3.x postgresql psycopg2 postgresql-11


    【解决方案1】:

    我的错。我在文档中没有注意到这一点:

    The function is mostly useful for commands that update the database: any result set returned by the query is discarded.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 2013-10-12
      • 2016-11-25
      • 1970-01-01
      • 2021-03-01
      • 2017-07-07
      相关资源
      最近更新 更多