Python3 psycopg2: «Нет результатов для извлечения» с использованием ВОЗВРАТА

#python #python-3.x #postgresql #psycopg2 #postgresql-11

#python #python-3.x #postgresql #psycopg2 #postgresql-11

Вопрос:

Я использую:

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

и я успешно вставляю строку, кроме курсора.fetchall() вызывает

 psycopg2.ProgrammingError: no results to fetch
  

даже когда я использую RETURNING внутри SQL для извлечения идентификатора.

Я узнал о cursor.description, но он пуст (cursor.description == None).

SQL работает корректно, используемый в терминале psql, возвращая идентификатор в соответствии с запросом.

код 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)
  

Ответ №1:

Моя ошибка. Я не заметил этого в документах:

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